본문 바로가기
백엔드/Java

알고리즘

by david100gom 2024. 4. 16.

문자정렬

// 문자역순
String a = "abcd";
 
StringBuffer sb = new StringBuffer();
 
for(int i = a.length()-1 ; i >= 0; i--) {
    sb.append(a.substring(i, i+1));
}
System.out.print("==>"+sb.toString());
 
 
// 자음끼리 자리교환
String[] ab = {"a","e","i","o","u"};
String input = "hello";
 
List<Integer> list = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
 
for(int i = 0 ; i < input.length(); i++) {
     
    int b = 0;
    for(int j = 0; j < ab.length; j++) {
 
        if(!ab[j].equals(input.substring(i, i+1))) {
            b++;
        }
 
    }
 
    if(b == ab.length) {
        list.add(i);
        list2.add(i);
    }
 
}
 
char[] t = input.toCharArray();
char[] t2 = input.toCharArray();
 
Collections.reverse(list);
 
int i = 0;
 
for(Integer abc : list) {
    t2[list2.get(i)] = t[abc];
    i++;
}
 
System.out.print("==>"+Arrays.toString(list.toArray()));
System.out.print("==>"+Arrays.toString(t));
System.out.print("==>"+String.valueOf(t2));

 

BigDecimal 비교

String[] s = new String[n]; 
 
Arrays.sort(s, Collections.reverseOrder(new Comparator<String>() {
       @Override
       public int compare(String a1, String a2) {
            //convert to big decimal inside comparator
            //so permanent string values are never changed
            //aka you only use the BigDecimal values to
            //compare the strings!
            if(a1 == null || a2 == null) {
                return 0;
            }
                 
            BigDecimal a = new BigDecimal(a1);
            BigDecimal b = new BigDecimal(a2);
            return a.compareTo(b);
       }
 }));

collections.sort

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
  
  
public class JavaCompareTest {
  
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        List<User> users = getCreateUsers();
  
        System.out.println("===== 정렬 하기전 =====");
        for (User temp : users) {
            System.out.println(temp);
        }
  
        Collections.sort(users, new NameAscCompare());
        System.out.printf("\n\n===== 문자 오름 차순 정렬 =====\n");
        for (User temp : users) {
            System.out.println(temp);
        }
  
        Collections.sort(users, new NameDescCompare());
        System.out.printf("\n\n===== 문자 내림 차순 정렬 =====\n");
        for (User temp : users) {
            System.out.println(temp);
        }
  
        Collections.sort(users, new NoAscCompare());
        System.out.printf("\n\n===== 숫자 오름 차순 정렬 =====\n");
        for (User temp : users) {
            System.out.println(temp);
        }
  
        Collections.sort(users, new NoDescCompare());
        System.out.printf("\n\n===== 숫자 내림 차순 정렬 =====\n");
        for (User temp : users) {
            System.out.println(temp);
        }
    }
  
  
    /**
     * User Data Create
     * @return
     */
     private static List<User> getCreateUsers() {
        // TODO Auto-generated method stub
         List<User> users = new ArrayList<User>();
  
         User user = new User();
         user.setName("고철수");
         user.setAddress("경기도 성남시 분당구");
         user.setPhone("010-1234-0192");
         user.setNo(1);
         users.add(user);
  
  
         user = new User();
         user.setName("박영희");
         user.setAddress("부산 해운대");
         user.setPhone("010-4234-0192");
         user.setNo(2);
         users.add(user);
  
  
         user = new User();
         user.setName("감수왕");
         user.setAddress("충북 제천");
         user.setPhone("010-7234-0192");
         user.setNo(3);
         users.add(user);
  
  
         user = new User();
         user.setName("이사람");
         user.setAddress("강원도 영울");
         user.setPhone("010-0234-0192");
         user.setNo(4);
         users.add(user);
        return users;
    }
  
  
     /**
      * 이름 오름차순
      * @author falbb
      *
      */
    static class NameAscCompare implements Comparator<User> {
  
        /**
         * 오름차순(ASC)
         */
        @Override
        public int compare(User arg0, User arg1) {
            // TODO Auto-generated method stub
            return arg0.getName().compareTo(arg1.getName());
        }
  
    }
  
    /**
     * 이름 내림차순
     * @author falbb
     *
     */
    static class NameDescCompare implements Comparator<User> {
  
        /**
         * 내림차순(DESC)
         */
        @Override
        public int compare(User arg0, User arg1) {
            // TODO Auto-generated method stub
            return arg1.getName().compareTo(arg0.getName());
        }
  
    }
  
     /**
      * No 오름차순
      * @author falbb
      *
      */
    static class NoAscCompare implements Comparator<User> {
  
        /**
         * 오름차순(ASC)
         */
        @Override
        public int compare(User arg0, User arg1) {
            // TODO Auto-generated method stub
            return arg0.getNo() < arg1.getNo() ? -1 : arg0.getNo() > arg1.getNo() ? 1:0;
        }
  
    }
  
    /**
     * No 내림차순
     * @author falbb
     *
     */
    static class NoDescCompare implements Comparator<User> {
  
        /**
         * 내림차순(DESC)
         */
        @Override
        public int compare(User arg0, User arg1) {
            // TODO Auto-generated method stub
            return arg0.getNo() > arg1.getNo() ? -1 : arg0.getNo() < arg1.getNo() ? 1:0;
        }
  
    }
  
  
}
 
// 문자열 비교compareTo처럼 숫자도 비교 해서 결과 값을 -1, 0, 1을 리턴 해주면 됩니다.
// -1:작다
// 0:같다
// 1:크다

깊이 우선 탐색(DFS, Depth First Search) : http://blog.eairship.kr/268

MD5, SHA-256

// MD5
 
public String testMD5(String str){
     
    String MD5 = "";
 
    try{
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes());
        byte byteData[] = md.digest();
        StringBuffer sb = new StringBuffer();
 
        for(int i = 0 ; i < byteData.length ; i++){
            sb.append(Integer.toString((byteData[i]&0xff) + 0x100, 16).substring(1));
        }
 
        MD5 = sb.toString();
 
    }catch(NoSuchAlgorithmException e){
        e.printStackTrace();
        MD5 = null;
    }
 
    return MD5;
}
 
// SHA-256
 
public String testSHA256(String str){
 
    String SHA = "";
 
    try{
 
        MessageDigest sh = MessageDigest.getInstance("SHA-256");
        sh.update(str.getBytes());
        byte byteData[] = sh.digest();
        StringBuffer sb = new StringBuffer();
 
        for(int i = 0 ; i < byteData.length ; i++){
            sb.append(Integer.toString((byteData[i]&0xff) + 0x100, 16).substring(1));
        }
 
        SHA = sb.toString();
 
    }catch(NoSuchAlgorithmException e){
        e.printStackTrace();
        SHA = null;
    }
 
    return SHA;
}

Prime Number

void checkPrime(int... numbers) {       
         
    for (int number : numbers) {           
        if (BigInteger.valueOf(number).isProbablePrime(1)) {
            System.out.print(number + " ");
        }
    }
         
    System.out.println();
}

댓글