zoukankan      html  css  js  c++  java
  • Cipe Coding Summary Part2

    25. Matrix Position
    Given an NxN matrix with unique integers :Find and print positions of all numbers such that it is the biggest in its row and also the smallest in its column . e.g. : In 3 x 3 with elements 
    1 2 3 .
    4 5 6 
    7 8 9 . 
    the number is 3 and position (1,3)

    Steps

    brute force, first find row find and to see if its the col min

    26. Replace String
    Froma given string, replace all instances of 'a' with 'one' and 'A' with 'ONE'.
    Example Input: " A boy is playing in a garden"
    Example Output: " ONE boy is playing in onegarden"
    -- Not that 'A' and 'a' are to be replaced only when theyare single characters, not as part of another word.

    Steps

    s.replaceAll("\b(a)", "one"),   match word with boundary


    27. Replace Words
    Given a string. Replace the words whose length>=4and is even, with a space between the two equal halves of the word. Consideronly alphabets for finding the evenness of the word 
    I/P "A person can't walk in this street" 
    O/P "A per son ca n't wa lk in th is str eet"

    s.toCharArray

    注意substring的index就行

    28. Replace AEIOU
    Replace a,e,i,o,u with A,E,I,O,U.
    At most four eligible letters from the rear of the string are replaced.
    The first three eligible letters in the string are always exempted from replacement.

    Steps

    replace char start from the end of the string


    29. Security Keypad
    There is a security keypad at the entrance ofa building. It has 9 numbers 1 - 9 in a 3x3 matrix format. 
    1 2 3 
    4 5 6 
    7 8 9 
    The security has decided to allow one digit error for a person but that digitshould be horizontal or vertical. Example: for 5 the user is allowed to enter2, 4, 6, 8 or for 4 the user is allowed to enter 1, 5, 7. IF the security codeto enter is 1478 and if the user enters 1178 he should be allowed. Write afunction to take security code from the user and print out if he should beallowed or not.

    找规律,相邻的数字绝对值差只有可能是 3 or 1, 用 Math.abs 判定是否是相邻数字即可


    30. Calendar
    Get a date (mon/day/year) from user. Print exact the week of dates (Sun to Sat). ex) input: 2/20/2001 if the day is Wednesday 
    output: Sunday 2/17/2001 . 
    Monday 2/18/2001 
    Tuesday 2/19/2001 
    Wednesday 2/20/2001 
    Thursday 2/21/2001 
    Friday 2/22/2001 
    Saturday 2/23/2002

     1 static void printWeek(String str) {
     2     SimpleDateFormat ft = new SimpleDateFormat("MM/dd/yyyy");
     3     SimpleDateFormat sft = new SimpleDateFormat("E MM/dd/yyyy");
     4     try {
     5         Date date = ft.parse(str);
     6         Calendar cal = new GregorianCalendar();
     7         cal.setTime(date);
     8         int temp = cal.get(cal.DAY_OF_WEEK);
     9         while (temp > 0) {
    10             cal.add(Calendar.DATE, -1);
    11             temp--;
    12         }
    13         while (temp < 7) {
    14             cal.add(Calendar.DATE, 1);
    15             System.out.println(sft.format(cal.getTime()));
    16             temp++;
    17         }
    18     }
    19     catch (ParseException e) {
    20         System.out.println("Unparsable");
    21     }
    22 
    23 }


    31. Seeds Number
    Find the seed of a number. 
    Eg : 1716 = 143*1*4*3 =1716 so 143 is the seed of 1716. find all possible seed for a given number.


    32. Tic Tac Toe
    N*N matrix is given with input red or black.You can move horizontally, vertically or diagonally. If 3 consecutive same color found, that color will get 1 point. So if 4 red are vertically then pointis 2. Find the winner.

    遍历一遍board


    33. Fill a “magic square”matrix.
    A magic square of order n is an arrangement of thenumbers from 1 to n^2 in an n by n matrix with each number occurring exactlyonce so that each row, each column and each main diagonal has the same sum. Then should be an odd number. In the middle cell of the top row, fill number 1.Then go to above row and right column, and fill following number 2. If it’s outof boundary, go to the opposite row or column. If the next cell is alreadyoccupied, go to the cell below this cell and fill following number. An exampleof 5*5 grid is like this for the first 9 numbers:
    0 0 1 8 0
    0 5 7 0 0
    4 6 0 0 0
    0 0 0 0 3
    0 0 0 2 9

     1 public static int[][] createMS(int n) {
     2     if (n <= 0) return null;
     3     int[][] res = new int[n][n];
     4     // initial position of 1
     5     int x = 0;
     6     int y = n / 2; // n is odd
     7     res[x][y] = 1;
     8     for (int i = 2; i <= n * n; i++) {
     9         int newX = (x + n - 1) % n;    // use (x - 1 + n) instead of (x - 1) 
    10                                     // to avoid overflow 
    11         int newY = (y + 1) % n;
    12         if (res[newX][newY] == 0) {
    13             res[newX][newY] = i;
    14         } else {
    15             newX = (x + 1) % n;
    16             newY = y;
    17             if (res[newX][newY] != 0) {    // error
    18                 System.out.println("invalid");
    19                 return null;
    20             }
    21             res[newX][newY] = i;
    22         }
    23         x = newX;
    24         y = newY;
    25     }
    26     return res;
    27 }


    34. Bull and Cows Game
    There’s a word guessing game. One personthink a word, and the other one guess a word, both words have the same length.The person should return the number of bulls and cows for the guessing. Bullsrepresent the number of same characters in the same spots, whereas cowsrepresent the number of characters guessed right but in the wrong spots. Writea program with two input strings, return the number of bulls and cows.

    Arrays.sort method

    35. Palindromes
    Print all palindromes of size greater than orequal to 3 of a given string. (How to do it with DP)?


    36. Unique Number
    Write, efficient code for extracting uniqueelements from a sorted list of array. e.g. (1, 1, 3, 3, 3, 5, 5, 5, 9, 9, 9, 9)-> (1, 3, 5, 9).

    arr.remove(Index);


    37. Subtraction of two Arrays
    Suppose you want to do the subtraction of twonumbers. Each digit of the numbers is divided and put in an array. Like A=[1,2, 3, 4, 5], B=[4, 5, 3, 5]. You should output an array C=[7, 8, 1, 0].Remember that your machine can’t hand numbers larger than 20.

    public static List<Integer> substractArray(int[] a, int[] b) {
        if(a == null || b == null)    return null;
        List<Integer> res = new ArrayList<Integer>();
        
        int ptr1 = a.length - 1;
        int ptr2 = b.length - 1;
        int carry = 0;
        int diff = 0;
        while(ptr1>=0 || ptr2>=0) {
            if(ptr2 >= 0) {
                diff = (10 + a[ptr1] - b[ptr2] - carry);
                carry = diff/10 == 1 ? 0 : 1;
                res.add(0, diff%10);
                ptr2--;
                ptr1--;
            }
            else if(ptr1 >= 0) {
                if(ptr1 == 0 && carry == 1 && a[ptr1] == 1) {    //special case first digits = 1;
                    ptr1 --;
                    continue;
                }
                diff = (10 + a[ptr1] - carry);
                carry = diff/10 == 1 ? 0 : 1;    
                res.add(0, diff%10);
                ptr1--;
            }                    
        }
        return res;
    }


    38. Basketball Hit Rate
    The hit rate of the basketball game is givenby the number of hits divided by the number of chances. For example, you have 73 chances but hit 15 times, then your hit rate is 15/73=0.205 (keep the last3 digits). On average, you have 4.5 chances in each basketball game. Assume thetotal number of games is 162. Write a function for a basketball player. He will input the number 
    of hits he has made, the number of chances he had, and the number of remaining games. The function should return the number of future hits, so that hecan refresh his hit rate to 0.45


    39. Clock Angle
    We are given a specific time(like 02:23), we need to get the angle between hour and minute(less than 180)

    String[] value = time.split(":");

    int hour = Integer.parseInt(value[0]);


    40. Jumper Game
    A NxN grid which contains either of 0-empty, 1 - player1, 2 - player 2. Given a position in the grid, find the longest jump path. For jump path, you can horizontally or vertically, you can jump on opponent cell and also the landing cell should be empty. No opponent cell can be jumped more than once. Write a function which takes grid and a specific position in the grid, and returns the longest possible number of jumps in the grid.


    41. Decimal Number
    Let the user enter a decimal number. Therange allowed is 0.0001 to 0.9999. Only four decimal places are allowed. Theoutput should be an irreducible fraction. E.g.: If the user enters 0.35,the irreducible fraction will be 7/20.

    辗转相除法 http://en.wikipedia.org/wiki/Euclidean_algorithm

     1 public static String fraction(double d) {
     2     // d is between 0.0001 to 0.9999
     3     int x = (int) (d * 10000);
     4     int gcd = findGCD(x, 10000);
     5     return x / gcd + " / " + 10000 / gcd; 
     6 }
     7 
     8 static int findGCD(int a, int b) {
     9     if (b == 0) return a;
    10     return findGCD(b, a % b);
    11 }

    42. Continuous Alphabets
    Printcontinuous alphabets from a sequence of arbitrary alphabets . @1point 3 acres
    For example: 
    Input: abcdefljdflsjflmnopflsjflasjftuvwxyz . Waral 
    Output: abcdef; mnop; tuvwxyz
    Input: AbcDefljdflsjflmnopflsjflasjftuvWxYz 
    Output: abcdef; mnop; tuvwxyz


    43. Substring Addition
    Write a program to add the substring. eg :say you have alist {1 7 6 3 5 8 9 } and user is entering a sum 16. Output should display(2-4) that is {7 6 3} cause 7+6+3=16.


    44. Balanced String
    Given a string that has{},[],() and characters.Check if the string is balanced. E.g. {a[(b)]} is balanced. {a[(b])} isunbalanced.

    Stack<Character> st = new Stack<Character>();


    45. RGBCompare
    Given a string of RGB value (rr, gg, bb)which represents in hexadecimal. Compare if rr or gg or bb is the biggest, or two of those values are equal and larger than the third one, or three values are equal with each other.


    46. Edge Detection
    Two-dimensional array representation of an image can also be represented by a one-dimensional array of W*H size, where W represent row and H represent column size and each cell represent pixel value of that image. You are also given a threshold X. For edge detection, you have to compute difference of a pixel value with each of it's adjacent pixel and find maximum of all differences. And finally compare if that maximum difference is greater than threshold X. if so, then that pixel is a edge pixel and have to display it.


    47. Plus Equal Number
    Given a number find whether the digits in the number can be used to form an equation with + and '='. That is if the number is 123, we can have a equation of 1+2=3. But even the number 17512 also forms theequation 12+5=17.


    48. Octal and Decimal Palindrome
    The decimal and octal values of some numbers are both palindromes sometimes. Find such numbers within a given range.

  • 相关阅读:
    代腾飞(为自己名字作诗)
    愈到老愈受用:人生成功生涯规划100诀
    漫步白沫江畔有感
    成功自有成功的方法和道理(一堂价值百万的课)
    你的终点在哪里?决定成功与否的十种智力
    为你痴狂
    苏竹青(帮别人名字作诗)
    何韵仪(帮别人名字作诗)
    腹有诗书又如何
    漫步茶马古道有感
  • 原文地址:https://www.cnblogs.com/superbo/p/4107320.html
Copyright © 2011-2022 走看看