JavaRush/Java Blog/Random EN/Java Challenges with a Trick: Hello Job Interviews!

Java Challenges with a Trick: Hello Job Interviews!

Published in the Random EN group
members
For CodeGym students , programming tasks, Java and validator are best friends. However, there comes a point for every development Padawan when you need to start going off the beaten track sometimes, coming up with mini-projects for yourself and preparing for interviews. At the interview, it would seem that exactly the same practical tasks in Java should be encountered as in the course. In most cases, it is, but some companies like to ask tricky questions or something unusual. In order not to be confused during the stressful moment of the interview, it is useful to try to solve such Java tasks on your own, at home.
Java Challenges with a Trick: Hello Job Interviews!  - 1
In this article, we will look at half a dozen of these tricky tasks. We recommend that you first read the condition and try to solve it yourself. And one more thing: do not forget to solve the Java problems from the course every day!

Java Challenge - 1: Creating an Infinite Loop from Scratch

Given a block of code. Complete it so that the cycle becomes infinite.
class ToInfinity {
    public static void main(String[] args) {

//впишите code сюда

        for (int i = start; i <= start + 1; i++) {
             /* тут должен быть бесконечный цикл, менять ничего нельзя*/
        }
    }
}
“Nothing complicated,” you say. Most likely, you have often found yourself in such a story: when solving problems in Java, you created an infinite loop and thought about how to get rid of it. Here it's the other way around. The trick is that the loop itself and the conditions for exiting it cannot be changed. There are only two iterations. However, they are quite enough to create an infinite loop. It looks like it should only work for two iterations, but it can be made infinite by using overflow. Already guessed how?

Solution

Due to overflow. Integer.MAX_VALUE- the maximum value that intcan be stored in Java. If you reach Integer.MAX_VALUEand increment this value, then you roll down to Integer.MIN_VALUE, that is, to the minimum value of Integer. Thus, to solve this Java problem, it is enough for us to assign a startvalue to the variable 1 less than the maximum value for the data type int. Task code in Java:
class ToInfinity {
    public static void main(String[] args) {
        int start = Integer.MAX_VALUE - 1;
        for (int i = start; i <= start + 1; i++) {
            //бесконечный цикл
            System.out.println(i); //убеждаемся в бесконечности цикла
        }
    }
}
What happens? We start at start=2147483645 (Integer.MAX_VALUE-1), on the next iteration the value becomes 2147483645, then 2147483646, then -2147483648, -2147483647... and so on.

Java task- 2. Create a comment to be executed

Well, here we are! From the very first lectures, we have heard that comments are not executed. That's why they are comments. We think that the solution to this problem for a Java programmer, even an experienced one, is not always obvious. However, there is one tricky way to make the Java machine "legally" run a comment for execution. Can you feel which way the wind is blowing? Try to guess!

Solution

The code for solving the problem in Java:
public class ExecutableComment {
    public static void main(String[] args) {
        // комментарий ниже будет выполнен!
        // \u000d System.out.println("выполняемый комментарий");
    }
}
If we type the code for this task in Java in the IDE, this is what we get:
выполняемый комментарий
The reason is that the Java compiler reads the Unicod character \u000das a newline, and reads our code as follows: The compiler decoded the code for solving the problem in Java:
public class ExecutableComment {
    public static void main(String[] args) {
        // the line below this gives an output
        // \u000d
        System.out.println("comment executed");
    }
}

Java Challenge - 3: Create a Named Loop

Another representative of the "practical programming tasks, Java in a spherical vacuum" series. In the sense that it is not clear why this is necessary, it is unlikely that the cycle feels offended by the fact that it is impersonal. Well, okay, something else is important: the language allows you to give the cycle a name.

Solution

Note: such "names" are known to some as "tags", which are not recommended to be used in practice. Java problem solving code demonstrating a named loop
public class NamedLoop {
    public static void main(String[] args) {
        loop1:
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                if (i == 3)
                    break loop1;
                System.out.println("i = " + i + " j = " + j);
            }
        }
    }
}
Here is what will be the output if you run the program:
i = 0 j = 0
i = 0 j = 1
i = 0 j = 2
i = 0 j = 3
i = 0 j = 4
i = 1 j = 0
i = 1 j = 1
i = 1 j = 2
i = 1 j = 3
i = 1 j = 4
i = 2 j = 0
i = 2 j = 1
i = 2 j = 2
i = 2 j = 3
i = 2 j = 4
Here you can also use continue to jump to the beginning of the named loop. And if necessary, you can use break(or continue) in a nested if-elsewith for-loop to break several loops with if-else. This will help avoid setting a lot of flags and testing them if-elsein order to figure out whether to continue or exit the inner loop.

Java problem - 4. About the only duplicate in an array of integers

Given an array (or ArrayListwhatever you prefer) of integers that contains elements Integerfrom 1 to 100. This array has one and only one duplicated element. How to find it? Such tasks for a Java programmer are more familiar than the previous three. Because it is not about knowing the subtleties of the language, which are almost never used, but about logic. The first unbridled impulse - to decide by brute force - disappears pretty quickly when the head turns on or there is the setting "I'm a programmer, I'm smart." The only bad thing is that in an interview, under stress, this may not happen. So think now before looking into the solution!

The solution algorithm is the following:

Calculate the sum of all numbers from 1 to 100. We think you know how to do this (for example, using the famous Gauss method) Now calculate the sum of the elements of your array or ArrayList’а. And… subtract the first amount from the second. Bingo! The resulting number is the value of the duplicate element. Java task solution code for ArrayList.
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class FindDuplicate {
    private static void findDuplicate(List<Integer> elements) {
//находим сумму всех уникальных элементов списка
        int distinctSum = elements.stream().distinct().mapToInt(e -> e).sum();
//находим сумму всех элементов списка
        int totalSum = elements.stream().mapToInt(e -> e).sum();
        System.out.println("Элемент, который повторяется : " + (totalSum - distinctSum));
    }

    public static void main(String[] args) {
//создаем список последовательных элементов на промежутке [1..101).
        List <Integer> elements = IntStream.range(1, 101).boxed().collect(Collectors.toList());
//устанавливаем элементу с индексом 53 meaning 23
        elements.set(53, 23);
        findDuplicate(elements);
    }
}
Another solution
import java.util.List;
import java.util.ArrayList;

public class Duplicate {

    public int findDuplicateNumber(List<Integer> numbers) {

        int highestNumber = numbers.size() - 1;
        int total = getSum(numbers);
        int duplicate = total - (highestNumber * (highestNumber + 1) / 2);
        return duplicate;
    }

    public int getSum(List<Integer> numbers) {

        int sum = 0;
        for (int num : numbers) {
            sum = sum + num;
        }
        return sum;
    }

    public static void main(String a[]) {
        List <Integer> numbers = new ArrayList <Integer>();
        for (int i = 1; i < 100; i++) {
            numbers.add(i);
        }
        //добавляем дубликат в список
        numbers.add(25);
        Duplicate dn = new Duplicate();
        System.out.println("Элемент, который повторяется: " + dn.findDuplicateNumber(numbers));
    }
}

Java problem - 5. About non-single duplicate in an array of integers

If the previous problem seemed too easy for you, then try to solve the following one: given a list of integers from 1 to 100. There are duplicates (more than one) in it. How to find elements that occur more than once (find the element itself and specify how many times it occurs)?

Solution

Here it is most logical to use a structure such as HashMap, since it stores data in key-value pairs. Java task solution code:
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class SomeDuplicates {
    private static void findDuplicates(List<Integer> elements) {
        HashMap <Integer, Integer > duplicates = new HashMap < >();
//заполняем Map duplicates значениями по принципу:
// ключ – meaning element, meaning – сколько раз он встречается
        elements.forEach(e -> duplicates.put(e, duplicates.get(e) == null ? 1 : duplicates.get(e) + 1));
//из duplicates убираем все элементы, которые встретorсь не более 1 раза,
//и сохраняем //результат в список (для удобства обработки на следующем шаге)
        List <Map.Entry <Integer, Integer> >
        result = duplicates.entrySet().stream().filter(d -> d.getValue() > 1).collect(Collectors.toList());
//выводим результат для всех элементов в списке result
        result.forEach(e -> System.out.println(String.format("Элемент %d  встречается %d раз", e.getKey(), e.getValue())));
    }

    public static void main(String[] args) {
        List <Integer> elements = IntStream.range(1, 101).boxed().collect(Collectors.toList());
        elements.set(97, 23);
        elements.set(27, 51);
        elements.set(99, 23);
        findDuplicates(elements);
    }
}

Conclusion

Practical tasks in Java are very different, and it is not known what unknown puzzle the interviewer will decide to give you. However, any reasonable employer understands that much more important than being able to solve tricky Java problems will be your ability to solve real practical problems , such as those that you will encounter while working. So solve them as much as possible. That's what CodeGym was created for. In preparing the article, materials geeksforgeeks were used
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet