My grandfather always predicted how old people would get, and right before he passed away he revealed his secret!
In honor of my grandfather's memory we will write a function using his formula!
Take a list of ages when each of your great-grandparent died.
Multiply each number by itself.
Add them all together.
Take the square root of the result.
Divide by two.
Example
predictAge(65, 60, 75, 55, 60, 63, 64, 45) === 86
Note: the result should be rounded down to the nearest integer.
import java.util.Arrays;
public class PredictYourAge {
public static int predictAge(int ... ages) {
// your code goes here
return (int) (Math.sqrt(Arrays.stream(ages).boxed().mapToInt(x -> x*x).sum())/2);
}
}
You are given a string of words (x), for each word within the string you need to turn the word 'inside out'. By this I mean the internal letters will move out, and the external letters move toward the centre.
If the word is even length, all letters will move. If the length is odd, you are expected to leave the 'middle' letter of the word where it is.
An example should clarify:
'taxi' would become 'atix' 'taxis' would become 'atxsi'
function insideOut(x){
var result = [];
for(var item of x.split(" ")){
var len = item.length;
if(len>3){
var middle = Math.floor(len/2);
if(len%2 == 0){
item = item.substring(0,middle).split("").reverse().join("").concat( item.substring(middle,len).split("").reverse("").join(""))
}else{
item = item.substring(0,middle).split("").reverse().join("").concat(item.substring(middle,middle+1)).concat( item.substring(middle+1,len).split("").reverse("").join(""))
}
}
result.push(item);
}
return result.join(" ");
}
Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_').
Examples:
solution('abc') // should return ['ab', 'c_']
solution('abcdef') // should return ['ab', 'cd', 'ef']
function solution(str){
var result = [];
while(str.length >1){
result.push(str.substring(0,2))
str = str.substring(2,str.length);
}
if(str.length !== 0)
result.push(str+"_")
return result;
}
Complete the solution so that it strips all text that follows any of a set of comment markers passed in. Any whitespace at the end of the line should also be stripped out.
Example:
Given an input string of:
apples, pears # and bananas
grapes
bananas !apples
The output expected would be:
apples, pears
grapes
bananas
The code would be called like so:
var result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"])
// result should == "apples, pears\ngrapes\nbananas"
function solution(input, markers){
var comments = input.split('\n');
for (var i in markers) {
for (var j in comments) {
var line = null;
var idx = comments[j].indexOf(markers[i]);
if (idx >= 0) {
comments[j] = comments[j].substring(0, idx).trim();
}
}
}
return comments.join('\n');
}
When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said
Description:
Give you two arrays arr1 and arr2. They have the same length(length>=2). The elements of two arrays always be integer.
Sort arr1 according to the ascending order of arr2; Sort arr2 according to the ascending order of arr1. Description is not easy to understand, for example:
arr1=[5,4,3,2,1],
arr2=[6,5,7,8,9]
Let us try to sorting arr1. First, we need know the ascending order of arr2:
[5,6,7,8,9]
We can see, after sort arr2 to ascending order, some elements' index are changed:
unsort arr2 ascending order arr2
[6,5,7,8,9]---> [5,6,7,8,9]
index0(6) ---> index1
index1(5) ---> index0
index2(7) index2(no change)
index3(8) index3(no change)
index4(9) index4(no change)
So, wo need according to these changes to sorting arr1:
unsort arr1 sorted arr1
[5,4,3,2,1]---> [4,5,3,2,1]
index0(5) ---> index1
index1(4) ---> index0
index2(3) index2(no change)
index3(2) index3(no change)
index4(1) index4(no change)
So: sorted arr1= [4,5,3,2,1]
And then, we sorting arr2 with the same process:
unsort arr1 ascending order arr1
[5,4,3,2,1]---> [1,2,3,4,5]
index0(5) ---> index4
index1(4) ---> index3
index2(3) index2(no change)
index3(2) ---> index1
index4(1) ---> index0
unsort arr2 sorted arr2
[6,5,7,8,9]---> [9,8,7,5,6]
index0(6) ---> index4
index1(5) ---> index3
index2(7) index2(no change)
index3(8) ---> index1
index4(9) ---> index0
So: sorted arr2= [9,8,7,5,6]
Finally, returns the sorted arrays by a 2D array: [sorted arr1, sorted arr2]
Note: In ascending order sorting process(not the final sort), if some elements have same value, sort them according to their index; You can modify the original array, but I advise you not to do that. ;-)
Some Examples and explain
sortArrays([5,4,3,2,1],[6,5,7,8,9]) should return
[[4,5,3,2,1],[9,8,7,5,6]]
sortArrays([2,1,3,4,5],[5,6,7,8,9]) should return
[[2,1,3,4,5],[6,5,7,8,9]]
sortArrays([5,6,9,2,6,5],[3,6,7,4,8,1]) should return
[[5,5,2,6,9,6],[4,3,1,6,8,7]]
import java.util.Comparator;
import java.util.stream.IntStream;
public class ArraySorter {
private static int [] sort(int [] target, int [] sortby ) {
return IntStream.range(0, target.length).boxed()
.sorted(Comparator.comparing(i->sortby[i]))
.mapToInt(i->target[i]).toArray();
}
public static int[][] sortTwoArrays(int[] arr1, int[] arr2) {
return new int [][] {sort(arr1,arr2),sort(arr2,arr1)};
}
}
Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n^3, the cube above will have volume of (n-1)^3 and so on until the top which will have a volume of 1^3.
You are given the total volume m of the building. Being given m can you find the number n of cubes you will have to build?
The parameter of the function findNb (find_nb, find-nb, findNb) will be an integer m and you have to return the integer n such as n^3 + (n-1)^3 + ... + 1^3 = m if such a n exists or -1 if there is no such n.
Examples:
findNb(1071225) --> 45
findNb(91716553919377) --> -1
public class ASum {
public static long findNb(long m) {
// your code
long sum = 0;
int n = 0;
while (sum < m)
sum += (long) Math.pow(++n, 3);
return sum == m ? n : -1;
}
}
Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in an array like so: [index1, index2].
For the purposes of this kata, some tests may have multiple answers; any valid solutions will be accepted.
The input will always be valid
(numbers will be an array of length 2 or greater, and all of the items will be numbers; target will always be the sum of two different items from that array).
public class Solution
{
public static int[] twoSum(final int[] numbers, int target)
{
for(int i = 0; i < numbers.length;i++ ) {
for(int j = i + 1; j < numbers.length;j++) {
if(numbers[i] + numbers[j] == target) {
return new int []{i,j};
}
}
}
return null; // Do your magic!
}
}
The cable will be symbolized with a combination of the following characters: -, _, =.
Each character has a different length: - is of length 1, _ of length 2 and = of length 3.
Sometimes the cable is making a loop. This will be symbolized with brackets.
When you have reached a closing bracket ), you have to go back to the corresponding opening bracket and count the length again -> this represents a loop.
If a cable is broken, meaning number of ( is not equal to number of ), you must throw a BracketException of type RuntimeException that you must implement yourself.
If the cable has a node, meaning a different character is detected on the input string, throw a NodeException of type RuntimeException (implement it as well)
If a cable is both broken and contains nodes then it should throw the exception that can be first detected and confirmed.
Good luck and keep an eye on the performance of your code - suboptimal solutions may time out in the Submit tests ;)
동작은 하는데 에러처리등을 직접해줘야 하는데 .. 너무 정보가 부족하다
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.stream.Collectors;
public class Cable {
public static int parse(String x) {
int result = 0;
if (x.equals("-")) {
result = 1;
} else if (x.equals("_")) {
result = 2;
} else {
result = 3;
}
return result;
}
public static BigInteger solve(String cable) throws Exception {
Stack<String> stack = new Stack<>();
String[] cables = cable.split("");
for (String c : cables) {
if (c.equals(")")) {
String temp = null;
List<String> internal = new ArrayList<>();
while (!(temp = stack.pop()).equals("(")) {
internal.add(temp);
}
stack.addAll(internal);
stack.addAll(internal);
} else {
stack.push(c);
}
}
return BigInteger.valueOf(stack.stream().mapToInt(Cable::parse).sum());
}
}
가장 추천을 많이 받은 풀이
import java.util.*;
import java.math.BigInteger;
class BracketException extends RuntimeException {}
class NodeException extends RuntimeException {}
public class Cable {
final private static BigInteger TWO = new BigInteger("2");
public static BigInteger calculateLength(String cable){
BigInteger tot = BigInteger.ZERO;
int lvl = 0,
f = 0;
for (char c: cable.toCharArray()) {
f = 0;
switch (c) {
case '-': f = 1; break;
case '_': f = 2; break;
case '=': f = 3; break;
case '(': lvl += 1; break;
case ')': lvl -= 1; if (lvl<0) throw new BracketException(); break;
default : throw new NodeException();
}
if (f!=0) tot = tot.add( TWO.pow(lvl).multiply( BigInteger.valueOf(f) ));
}
if (lvl!=0) throw new BracketException();
return tot;
}
}
Given a list of languages and your respective test results, return the list of languages where your test score is at least 60, in descending order of the results.