A common exercise, when you're learning a new language, is to make a guessing game. It's a great way to learn control structures, IO, the works.
This is taking the guessing game to a whole new level. This time, you're the one playing the guessing game. And the guessing game is Math.random().
The task is really simple. You make a guess, Math.random() does it's thing, and if you're right 5 times out of 5, you win!
Hint: You guess first.
import java.lang.reflect.*;
import java.util.Random;
public class Psychic {
public static double guess() {
try {
Field field = Class.forName("java.lang.Math$RandomNumberGeneratorHolder")
.getDeclaredField("randomNumberGenerator");
field.setAccessible(true);
Random random = (Random) field.get(null);
random.setSeed(0);
} catch (Exception e) {
}
return new Random(0).nextDouble();
}
}
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.
Note: If the number is a multiple of both 3 and 5, only count it once.
Courtesy of ProjectEuler.net
import java.util.stream.IntStream;
public class Solution {
public int solution(int number) {
//TODO: Code stuff here
return IntStream.range(1, number).filter(x-> x%3==0 || x%5==0 ).sum();
}
}
Write a function to find if a number is lucky or not. If the sum of all digits is 0 or multiple of 9 then the number is lucky.
1892376 => 1+8+9+2+3+7+6 = 36. 36 is divisble by 9, hence number is lucky.
Function will return true for lucky numbers and false for others.
집에 너무 늦게 들어온데다가 이번주내내 잠을 못자서 너무 피곤한 관계로 낮은 레벨을 선택해서 품
어뷰징에 대해 고민이 조금 있긴 하지만, 한번 안하면 두번 안하는건 일도 아니기 때문이 쉬운문제라도 풀기로 한다.
import java.util.stream.Stream;
public class LuckyNumber {
public static boolean isLucky(long n) {
// is n lucky?
int result = Stream.of(String.valueOf(n).split("")).mapToInt(Integer::valueOf).sum();
return result % 9 == 0 || result == 0;
}
}
주어진 문제를 정직하게 풀었는데 가장 추천을 많이 받은 답변은 정말 간결하다. 쉬운문제도 많이 고민해볼 수 있도록해야 겠다.
public class LuckyNumber {
public static boolean isLucky(long n) {
return n % 9 == 0;
}
}
You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this "outlier" N.
Examples
[2, 4, 0, 100, 4, 11, 2602, 36]
Should return: 11 (the only odd number)
[160, 3, 1719, 19, 11, 13, -21]
Should return: 160 (the only even number)
static int find(int[] integers) throws Exception{
List<Integer> even = new ArrayList<Integer>();
List<Integer> odd = new ArrayList<Integer>();
for (int i : integers) {
if(i%2==0) {
even.add(i);
}else {
odd.add(i);
};
};
return even.size() == 1 ? even.get(0) : odd.get(0);
}
보면서 감탄한 가장 많은 추천을 받은 풀이
public static int find(int[] integers) {
// Since we are warned the array may be very large, we should avoid counting values any more than we need to.
// We only need the first 3 integers to determine whether we are chasing odds or evens.
// So, take the first 3 integers and compute the value of Math.abs(i) % 2 on each of them.
// It will be 0 for even numbers and 1 for odd numbers.
// Now, add them. If sum is 0 or 1, then we are chasing odds. If sum is 2 or 3, then we are chasing evens.
int sum = Arrays.stream(integers).limit(3).map(i -> Math.abs(i) % 2).sum();
int mod = (sum == 0 || sum == 1) ? 1 : 0;
return Arrays.stream(integers).parallel() // call parallel to get as much bang for the buck on a "large" array
.filter(n -> Math.abs(n) % 2 == mod).findFirst().getAsInt();
}
Create an endless stream of prime numbers - a bit like IntStream.of(2,3,5,7,11,13,17), but infinite. The stream must be able to produce 50 million primes in a few seconds.
당당하게 도전하고 ,당당하게 망했다 3시간동안 고민해봤는데 못풀겠다.
현재 레벨보다 높은 단계라 솔루션도 못본다. 포기하고 다른문제 풀어서 올릴까하다가
들인시간이 아까워서 주말에 다시 풀어보려고 올림
일단 오늘 풀이. 정답은 맞는데 타임아웃걸린다 !!
public class Primes {
public static IntStream stream() {
IntPredicate isPrime = (n) -> n > 1 && IntStream.rangeClosed(2, (int) Math.sqrt(n)).noneMatch(i -> n % i == 0);
return IntStream.iterate(2, i -> i + 1).filter(isPrime);
}
}
엣킨체를 이용해서 풀을 크게만들어서 시도해봤는데 작은 갯수를 짧은시간안에 풀이하는게 동작하지 않는다.
Freddy has a really fat left pinky finger, and every time Freddy tries to type an A, he accidentally hits the CapsLock key!
Given a string that Freddy wants to type, emulate the keyboard misses where each A supposedly pressed is replaced with CapsLock, and return the string that Freddy actually types. It doesn't matter if the A in the string is capitalized or not. When CapsLock is enabled, capitalization is reversed, but punctuation is not affected.
Examples:
"The quick brown fox jumps over the lazy dog."
-> "The quick brown fox jumps over the lZY DOG."
"The end of the institution, maintenance, and administration of government, is to secure the existence of the body politic, to protect it, and to furnish the individuals who compose it with the power of enjoying in safety and tranquillity their natural rights, and the blessings of life: and whenever these great objects are not obtained, the people have a right to alter the government, and to take measures necessary for their safety, prosperity and happiness."
-> "The end of the institution, mINTENnce, ND dministrTION OF GOVERNMENT, IS TO SECURE THE EXISTENCE OF THE BODY POLITIC, TO PROTECT IT, nd to furnish the individuLS WHO COMPOSE IT WITH THE POWER OF ENJOYING IN Sfety ND TRnquillity their nTURl rights, ND THE BLESSINGS OF LIFE: nd whenever these greT OBJECTS re not obtINED, THE PEOPLE Hve RIGHT TO lter the government, ND TO Tke meSURES NECESSry for their sFETY, PROSPERITY nd hPPINESS."
"aAaaaaAaaaAAaAa"
-> ""
If the given string is null, return null.
If the given string is "", the answer should be evident.
Happy coding!
public class Kata {
public static String fatFingers(String str) {
if (str == null) return null;
boolean capsLock = false;
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (c == 'A' || c == 'a') {
capsLock = capsLock ? false : true;
}
else if (capsLock) {
if (Character.isUpperCase(c))
chars[i] = Character.toLowerCase(c);
else if (Character.isLowerCase(c))
chars[i] = Character.toUpperCase(c);
}
}
String result = new String(chars);
result = result.replaceAll("[Aa]","");
return result;
}
}
Hint: You're not meant to calculate the factorial. Find another way to find the number of zeros.
팩토리얼을 구하고 0의 갯수를 세면... 타임 초과가 난다 이틀 연속 타임 초과
public static int zeros(int n) {
if(n==0) return 0;
BigInteger ten = new BigInteger("10");
BigInteger fact = Stream.iterate(BigInteger.ONE, x->x.add(BigInteger.ONE)).limit(n).reduce(BigInteger::multiply).get();
int trail = 0;
while(fact.divideAndRemainder(ten)[1] == BigInteger.ZERO) {
fact = fact.divide(ten);
trail++;
}
return trail;
}
시간 고려해서 한 풀이
public static int zeros(int n) {
int trail = 0;
int i = 1;
double temp = 0d;
do {
temp = n / Math.pow(5, i++);
trail += Math.floor(temp);
}while(temp > 0);
return trail;
}
The year is 1214. One night, Pope Innocent III awakens to find the the archangel Gabriel floating before him. Gabriel thunders to the pope:
Gather all of the learned men in Pisa, especially Leonardo Fibonacci. In order for the crusades in the holy lands to be successful, these men must calculate the millionth number in Fibonacci's recurrence. Fail to do this, and your armies will never reclaim the holy land. It is His will.
The angel then vanishes in an explosion of white light.
Pope Innocent III sits in his bed in awe. How much is a million? he thinks to himself. He never was very good at math.
He tries writing the number down, but because everyone in Europe is still using Roman numerals at this moment in history, he cannot represent this number. If he only knew about the invention of zero, it might make this sort of thing easier.
He decides to go back to bed. He consoles himself, The Lord would never challenge me thus; this must have been some deceit by the devil. A pretty horrendous nightmare, to be sure.
Pope Innocent III's armies would go on to conquer Constantinople (now Istanbul), but they would never reclaim the holy land as he desired.
In this kata you will have to calculate fib(n) where:
fib(0) := 0
fib(1) := 1
fin(n + 2) := fib(n + 1) + fib(n)
Write an algorithm that can handle n where 1000000 ≤ n ≤ 1500000.
Your algorithm must output the exact integer answer, to full precision. Also, it must correctly handle negative numbers as input.
HINT I: Can you rearrange the equation fib(n + 2) = fib(n + 1) + fib(n) to find fib(n) if you already know fin(n + 1) and fib(n + 2)? Use this to reason what value fib has to have for negative values.
HINT II: See http://mitpress.mit.edu/sicp/chapter1/node15.html
타임오버 나왔다. 대칭이용해서 음수 까지는 잘처리했는데 피보나치 구하는 방식자체가 틀린것 같다.
import java.math.BigInteger;
import java.util.stream.Stream;
public class Fibonacci {
public static BigInteger fib(BigInteger n) {
// ...
if(n.signum() == 0) {
return BigInteger.ZERO;
}
BigInteger result = Stream.iterate(new BigInteger []{ BigInteger.ONE, BigInteger.ONE }, p-> new BigInteger[]{ p[1], p[0].add(p[1]) }).limit(n.abs().longValue()).reduce((a, b) -> b).get()[0];
if(n.signum() == -1 && n.abs().mod(new BigInteger("2")).equals(BigInteger.ZERO)) return result.negate();
return result;
}
}