Create a simple calculator that given a string of operators (+ - * and /) and numbers separated by spaces returns the value of that expression
Example:
Calculator.evaluate("2 / 2 + 3 * 4 - 6") // => 7
Remember about the order of operations! Multiplications and divisions have a higher priority and should be performed left-to-right. Additions and subtractions have a lower priority and should also be performed left-to-right.
A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example ("12, 13, 15-17")
Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format.
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, drinks it and gets to the end of the queue as two Leonards, and so on.
For example, Penny drinks the third can of cola and the queue will look like this:
Write a program that will return the name of the person who will drink the n-th cola.
Note that in the very beginning the queue looks like that:
Sheldon, Leonard, Penny, Rajesh, Howard
##Input
The input data consist of an array which contains at least 1 name, and single integer n.
(1 ≤ n ≤ 1000000000).
##Output / Examples Return the single line — the name of the person who drinks the n-th can of cola. The cans are numbered starting from 1. Please note that you should spell the names like this: "Sheldon", "Leonard", "Penny", "Rajesh", "Howard" (without the quotes). In that order precisely the friends are in the queue initially.
In mathematics, the factorial of integer n is written as n!. It is equal to the product of n and every integer preceding it. For example: 5! = 1 x 2 x 3 x 4 x 5 = 120
Your mission is simple: write a function that takes an integer n and returns the value of n!.
You are guaranteed an integer argument. For any values outside the non-negative range, return null, nil or None (return an empty string "" in C and C++). For non-negative numbers a full length number is expected for example, return 25! = "15511210043330985984000000" as a string.
BigInteger가 없었다면 꽤나 어려울것 같지만
다른 사람들 풀이를 봐도 대다수가 BigInteger 를이용해서 풀었더라.
import java.math.BigInteger;
public class Kata
{
public static String Factorial(int n) {
BigInteger result = BigInteger.valueOf(1);
for (int i = 1; i <= n; i++)
result = result.multiply(BigInteger.valueOf(i));
return result.toString();
}
}
You are given a string s. Every letter in s appears once.
Consider all strings formed by rearranging the letters in s. After ordering these strings in dictionary order, return the middle term. (If the sequence has a even length n, define its middle term to be the (n/2)th term.)
Example
For s = "abc", the result should be "bac".
The permutations in order are:
"abc", "acb", "bac", "bca", "cab", "cba"
So, The middle term is "bac".
Input/Output
[input] string s
unique letters (2 <= length <= 26)
[output] a string
middle permutation.
처음 푼 풀이
모든 순열 뽑고 가운데 값 찾는다
4kyh 까지 퍼포먼스를 전혀 고려하지 않았는데
처음으로 타임아웃을 만났다.
public static List<String> generater(String input) {
List<String> reslut = new ArrayList<String>();
MiddlePermutation.permutation("", input, reslut);
return reslut;
}
private static void permutation(String chars, String input, List<String> result) {
if (input.isEmpty()) {
result.add(chars + input);
return;
}
for (int i = 0; i < input.length(); i++) {
permutation(chars + input.charAt(i), input.substring(0, i) + input.substring(i + 1), result);
}
}
public static String findMidPerm(String strng) {
// your code here!
List<String> result =MiddlePermutation.generater(strng);
Collections.sort(result);
return result.get((result.size() / 2) - 1);
}
성능을 고려해서 다시 짰다.
(1) 먼저 모든 순열을 구해 정렬 하는 것보다 문자를 정렬하는 것이 좋다.
(모든 순열을 구한 뒤 정렬 할 경우 문자열이 길어질 수록 정렬해야 할 순열이 많아진다. )
(2) 문자열이 짝수일 경우 중간에 있는 문자 + 나머지의 역순
(3) 문자열이 홀수일 경우 중간문자 + 나머지는 짝수이므로 (2) 를 다시한번 실행
홀수 일경우 불필요하게 정렬을 한번 더하고 있는데 오늘 생각보다 많은 시간을 소비해서 일단 넘어가자.
public static String findMidPerm(String strng) {
// your code here!
char [] temp = strng.toCharArray();
Arrays.sort(temp);
String sorted = new String(temp);
if(sorted.length()%2==0) {
int middle = sorted.length()/2-1;
StringBuilder remainder = new StringBuilder(sorted.substring(0,middle)+sorted.substring(middle+1));
return sorted.substring(middle,middle+1) + remainder.reverse().toString();
}else {
int middle = sorted.length()/2;
String remainder = sorted.substring(0,middle)+sorted.substring(middle+1);
return sorted.substring(middle,middle+1) + findMidPerm(remainder.toString());
}
}
This problem takes its name by arguably the most important event in the life of the ancient historian Josephus: according to his tale, he and his 40 soldiers were trapped in a cave by the Romans during a siege.
Refusing to surrender to the enemy, they instead opted for mass suicide, with a twist: they formed a circle and proceeded to kill one man every three, until one last man was left (and that it was supposed to kill himself to end the act).
Well, Josephus and another man were the last two and, as we now know every detail of the story, you may have correctly guessed that they didn't exactly follow through the original idea.
You are now to create a function that returns a Josephus permutation, taking as parameters the initial array/list of items to be permuted as if they were in a circle and counted out every k places until none remained.
Tips and notes: it helps to start counting from 1 up to n, instead of the usual range 0..n-1; k will always be >=1.
For example, with n=7 and k=3 josephus(7,3) should act this way.
[1,2,3,4,5,6,7] - initial sequence
[1,2,4,5,6,7] => 3 is counted out and goes into the result [3]
[1,2,4,5,7] => 6 is counted out and goes into the result [3,6]
[1,4,5,7] => 2 is counted out and goes into the result [3,6,2]
[1,4,5] => 7 is counted out and goes into the result [3,6,2,7]
[1,4] => 5 is counted out and goes into the result [3,6,2,7,5]
[4] => 1 is counted out and goes into the result [3,6,2,7,5,1]
[] => 4 is counted out and goes into the result [3,6,2,7,5,1,4]
So our final result is: josephus([1,2,3,4,5,6,7],3)==[3,6,2,7,5,1,4]
public static <T> List<T> josephusPermutation(final List<T> items, final int k) {
int current = 0;
List<T> result= new ArrayList<T>();
while (items.size() > 0) {
current = (current-1+k)%items.size();
/*
current+=k-1;
while(current > = items.size()) {
current -= items.size();
}
*/
result.add(items.remove(current));
}
return result;
}
1. 지금 다니고 있는 회사에서 하는 일을 잘하기 위해서 노력하는 것이 가장 좋은 공부다.
2. 회사에서 하는 일과 개인적으로 공부하는 내용을 최대한 근접시키기 위해서 노력하라.
3. 새로운 기술을 익히는 최선의 방법은 스스로 문제를 정의한 다음, 새로운 기술을 이용해서 그 문제를 풀어보는 것이다. 책을 읽거나 동영상을 보는 것은 그보다 하위수준의 방법이다.
4. 신기술을 좇는 메뚜기가 되지 말라.
5. 모든 것을 알아야 한다는 강박을 버려라. 미리 획득하는 지식의 99%는 무용지물이다. 필요할 때 필요한 기술을 익힐 수 있는 것이 능력이다. 그 능력을 키워라.
6. 이상한 나라의 앨리스에 나오는 토끼굴(rabbit hole)을 피하라. 카테고리이론을 알아야 함수형 언어를 쓸 수 있는게 아니고, 선형대수학을 공부해야 머신러닝을 할 수 있는게 아니다. 토끼굴에 빠져서 한없이 들어가다보면 비본질적인 공부에 시간을 허비하게 된다.
7. 겉만 핥는 것은 경박하지만 토끼굴에 빠지는 것은 우매하다. 둘 사이의 적당한 지점에서 균형을 잡는 것이 개발자의 능력이다.
8. 머리에 들어오지 않는 어려운 개념이나 용어는 자투리 시간을 이용해서 반복적으로 읽고 암기하라. 나중에 큰 그림을 공부할 때 도움이 된다.
9. 항상 겸손해야 하지만 동시에 자긍심을 가져라. 그대가 지금 작성한 코드, 지금 읽은 책, 지금 공부한 내용을 그대보다 잘 아는 사람은 지구상에 없다. 모든걸 알고 있는 것처럼 보이는 다른 사람들도 그대와 마찬가지로 불안해하고, 위축되고, 두려워하면서 살아가고 있다. 자긍심이란 그런 타인을 돕고자 하는 마음가짐의 다른 이름이다.
Write a function that receives two strings and returns n, where n is equal to the number of characters we should shift the first string forward to match the second.
For instance, take the strings "fatigue" and "tiguefa". In this case, the first string has been rotated 5 characters forward to produce the second string, so 5 would be returned.
If the second string isn't a valid rotation of the first string, the method returns -1.
Examples:
"coffee", "eecoff" => 2
"eecoff", "coffee" => 4
"moose", "Moose" => -1
"isn't", "'tisn" => 2
"Esham", "Esham" => 0
"dog", "god" => -1
public class CalculateRotation {
static int shiftedDiff(String first, String second){
for(int i=0; i< second.length(); i++){
if(second.equals(first))
return i;
second = second.substring(1)+second.charAt(0);
}
return -1;
}
}
나름 군더더기 없이 했다고 생각했는데
더 쉬운 방법이 있었다
가장 많은 추천을 받은 코드
public class CalculateRotation {
static int shiftedDiff(String first, String second){
if(first.length() != second.length())
return -1;
return (second+second).indexOf(first);
}
}