100 Programming Questions and answers. WIP

Today (when I started this file) is Sep 26 2021.
Question # Programming Language Question/Task Answer
#1 Java Force the User to Enter a number into Stdin. If the user fails to provide a numeric String that can be parsed to an integer make him stuck in an infinite loop until he provides such a String.
A static java function that answers the question.
                        
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    /// Force the User to enter a number. If he fails every time to provide a numeric string he will be stuck in an infinite loop.
    public static int force_user_integer_input_stdin(String request) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

        while (true) {
            try {
                System.out.print(request+": ");
                String age = bf.readLine();
                Integer parsedage = Integer.parseInt(age);
                return parsedage;
            } catch (NumberFormatException e) {
                System.out.println("you HAVE TO enter a number.");
            }
        }
    }

    public static void main(String[] args) throws IOException {
        int age = Main.force_user_integer_input_stdin("Please enter a number");
        System.out.println("yo entered: " + age);        
    }
}
                        
                    
python program ...
                        
parsed_integer: int
while True:
    userinput: str = input("please enter a number!")
    try:
        parsed_integer = int(userinput)
        break
    except:
        print(f"an Error was thrown, while parsing your input. please try again.")

print(f"{parsed_integer = }")
                        
                    
#2 Java/Python Render a Black and White Checkerboard Pattern onto an Image. Dont load that image from the Hard Drive, do the calculations to generate it in working memory! Display that image inside a GUI Window to the end user.
                        
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Image;

public class Main {

    public static BufferedImage checkerboard_pattern(int width, int height, int pixel_size) {
        var img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < img.getWidth(); x++) {
            for (int y = 0; y < img.getHeight(); y++) {
                if (((x / pixel_size + y / pixel_size) % 2) == 0) {
                    img.setRGB(x, y, 0xffffffff);
                } else {
                    img.setRGB(x, y, 0xff000000);
                }
            }
        }
        return img;
    }

    public static void show_image(Image image) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new JLabel(new ImageIcon(image)));
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        // pixel size is 10 in this case. If pixel size is set to 1 you get some weird
        // interference pattern ... at least on my screen.
        Main.show_image(Main.checkerboard_pattern(500, 500, 10));
    }
}
                        
                    
Java solution using awt (abstract window toolkit, a java GUI library):
Python solution using tkinter and PIL ImageTk, Image
                        
from tkinter import Tk, Label
from PIL import ImageTk, Image

root = Tk()
im = Image.new("RGB", (100, 100), color=(0, 0, 0))

for y in range(im.size[1]):
    for x in range(im.size[0]):
        sum = (x//10 + y//10) % 2
        if sum == 1:
            im.putpixel((x, y), (255, 255, 255))


display = ImageTk.PhotoImage(im)

imagelabel = Label(root)
#self.__imagelabel.config(image = pilimg)
imagelabel.config(image=display)
imagelabel.image = display
imagelabel.pack()

root.mainloop()
                        
                    
#3 Java Implement the rule 110 cellular automaton, render its result to an Image and display it inside a GUI Window to the end user.
Java solution using awt:
                        
import java.awt.image.BufferedImage;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {

    public static BufferedImage white_top_right(int width, int height) {
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        for (int y = 0; y < img.getHeight(); y++) {
            for (int x = 0; x < img.getWidth(); x++) {
                img.setRGB(x, y, 0xff000000); // set it black.
            }
        }
        img.setRGB(img.getWidth() - 1, 0, 0xffffffff); // set top right pixel white.
        return img;
    }

    public static void elementary_cellular_automaton(int rule, BufferedImage img, boolean wall) {
        assert rule <= 255;
        rule &= 0xff;
        int wall_int = wall ? 1 : 0;
        for (int y = 1; y < img.getHeight(); y++) {
            for (int x = 0; x < img.getWidth(); x++) {
                int row_above = y - 1;
                int current_pattern = 0;
                for (int z = -1; z < 2; z++) {
                    int shifted_x = x + z;
                    int block_above = wall_int;
                    if (shifted_x >= 0 && shifted_x < img.getWidth()) {
                        block_above = img.getRGB(shifted_x, row_above);
                        if (block_above == 0xffffffff) {
                            int shiftindex = 1 - z;
                            current_pattern |= 1 << shiftindex;
                        }
                    }
                }
                if ((rule & (1 << current_pattern)) != 0) {
                    img.setRGB(x, y, 0xffffffff);
                }
            }
        }

    }

    public static void show_image(Image img) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new JLabel(new ImageIcon(img)));
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        var rule110 = Main.white_top_right(500, 500);
        Main.elementary_cellular_automaton(110, rule110, false);
        var scaled = rule110.getScaledInstance(1000, 1000, BufferedImage.SCALE_FAST);
        Main.show_image(scaled);
    }
}                        
                        
                    
#4 Java
Step 1: What is the output of the following Code inside the Vector.java file?
                    
public class Vector {
    int x, y;

    public float lenght() {
        return (float) Math.sqrt((double) (x * x + y * y));
    }

    public Vector(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public static void main(String[] args) throws InterruptedException {

        Vector a = new Vector(1, 1);
        Vector b = new Vector(1, 1);
        System.out.println("(a == b): " + (a == b));
        System.out.println("a.equals(b): " + (a.equals(b)));

        Class<?> aclass = a.getClass();
        Class<?> bclass = b.getClass();

        System.out.println("aclass.equals(bclass): " + aclass.equals(bclass));
        try{
            Thread.sleep(5000);
        }catch(InterruptedException ie){
            System.err.println(ie);
        }
    }
}
                    
                
Step 2: Modify the equals function accordingly.
Step 1: Console Output:
(a == b): false
a.equals(b): false
aclass.equals(bclass): true
                    
Add the following method to the Vector class Body:
                            
    @Override
    public boolean equals(Object other){
        if(other == null){
            return false;
        }
        if (other.getClass() != this.getClass()){
            return false;
        }

        final Vector other_vec = (Vector) other;
        return other_vec.x == this.x && this.y == other_vec.y;
    }
                            
                        
Note the == still compares Memory adresses, so the output of the Code in this Question after the change above is:
(a == b): false
a.equals(b): true
aclass.equals(bclass): true
                        
Step 2: Modification.
#5 Java Write a program that prints out the first 45 Fibbonacci numbers.
Java solution:
                        
public class Main {
    
    //generate Fibbonacci numbers
    public static void main(String[] args) {
        int first = 1;
        int second = 2;
        for (int i=1; i<46; i++){
            System.out.println("the "+ i+". Fibbonacci Number is: "+ first);
            int next = first + second;
            first = second;
            second = next;
        }
    }
}
                        
                    
You see the largest Fibbonacci number that can be represented by a Java int (32 bit signed integer type) is the 45. Fibbonacci number: 1836311903.
#6 Java UI: Create a 10x10 grid out of 100 Buttons and print the coordinates inside the grid to the console, if the respective Button is pressed.
Java awt solution.
                        
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.Point;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.util.HashMap;

public class ButtonGrid implements ActionListener{
    static final int WIDTH = 10;
    static final int HEIGHT = 10;
    JFrame thisframe;
    HashMap<Point, JButton> buttonmap;

    {
        buttonmap = new HashMap<>();
        for(int y=0; y<HEIGHT; y++){
            for(int x=0; x<WIDTH; x++){
                String xfromat = String.format("%02d", x);
                String yfromat = String.format("%02d", y);
                String coordinate_format = "("+xfromat+","+yfromat+")";
                JButton btn = new JButton(coordinate_format);
                buttonmap.put(new Point(x,y), btn);
                btn.addActionListener(this);
            }
        }
    }

    {
        thisframe = new JFrame();
        thisframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    {
        thisframe.getContentPane().setLayout(new GridBagLayout());
        for (var entry: buttonmap.entrySet()){
            Point position = entry.getKey();
            JButton btn = entry.getValue();
            GridBagConstraints cons = new GridBagConstraints();
            cons.gridx = position.y;
            cons.gridy = position.x;
            thisframe.getContentPane().add(btn, cons);
        }
        thisframe.pack();
    }

    {
        //adding a test button for layout constraints...
        GridBagConstraints cons = new GridBagConstraints();
        cons.gridx = 0;
        cons.gridy = HEIGHT;
        cons.fill = GridBagConstraints.HORIZONTAL;
        cons.gridwidth = WIDTH;
        JButton btn = new JButton("GridBagConstraints.HORIZONTAL");
        thisframe.getContentPane().add(btn, cons);
    }
    public ButtonGrid(){
        this.thisframe.setVisible(true);
    }

    public static void main(String[] args) {
        new ButtonGrid();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        for(var entry: this.buttonmap.entrySet()){
            if (e.getSource() == entry.getValue()){
                System.out.println(entry.getKey().toString() + "was pressed");
            }
        }
    }
}
                        
                    
python tkinter solution.
                        
from tkinter import Tk, Button

WIDTH = 10
HEIGHT = 10

root = Tk()
for y in range(HEIGHT):
    for x in range(WIDTH):
        def generate_print_function(x: int, y: int):
            def the_print_function():
                print(f"Button {x=} {y=} pressed")
            return the_print_function

        btn = Button(root, text=f"{x = } {y = }",
                     command=generate_print_function(x, y))
        btn.grid(row=y, column=x)

root.mainloop()
                        
                    
#7 Java
What is the output of the following Java code?
                        
public class ExceptionsQuestion1 implements AutoCloseable{
    
    public void whatHappensNext() throws Exception{
        //throw new IllegalArgumentException();
        try(ExceptionsQuestion1 is = new ExceptionsQuestion1()){
            System.out.print("O");
        }finally{
            System.out.print("K");
        }
    }

    public String name;
    public static void main(String[] args) throws Exception {
        ExceptionsQuestion1 e1 = new ExceptionsQuestion1();
        e1.whatHappensNext();
        System.out.println("I");
        System.out.println(e1.name);
    }
    //executes before finally block.
    @Override
    public void close() throws Exception {
        System.out.print("L");
        
    }
}
                        
                    
Java answer. OLKI
null

The close() method is called before the programmer defined finally block of AutoCloseable. Since the implemented close() function throws an Exception this Eception has to be passed down to the main function.
#8 python
How to extract all the paths to .txt files with a python glob expression? When you have the following directory structure:
    
╰─ tree                                                
.
├── a
│   └── b
│       └── c
│           ├── random1_file.txt
│           └── random2_file.png
└── d
    └── e
        └── f
            └── random3_file.txt
    
Python solution using glob expressions: python interactive mode in "."
>>> import glob
>>> glob.glob("**/*.txt", recursive=True)
['d/e/f/random3_file.txt', 'a/b/c/randomtxt', 'a/b/c/random2_file.txt']
                        
#9 Java
Which of the following functions compiles? A)
                        
    public static int methodA(int g){
        if (g>5){
            return 2*g;
        }else{
            return null;
        }
    }
                        
                    
B)
                        
    public static int[] methodB(int g) {
        if (g>5){
            return new int[]{g*2};
        }else{
            return null;
        }
    }
                        
                    
C)
                    
    public static Integer methodC(int g){
        if (g > 5){
            return 2*g;
        }
        return null;
    }
                    
                
A), B), C)? The Options B) and C) compile. Option A) throws the following Compilation error:
                        
Type mismatch: cannot convert from null to int Java(16777235)
                        
                    
Personally I was kind of confused by that: int can not be converted from null but int[] can ... I prefer Kotlin null safety to eliminate a whole class of Exceptions/panics, and less knowledge/thinking about edge cases is required.
#10 (python)
What is the oldest known non trivial algorithm known to humans? Code it in python! The Euclidean algorithm. It finds the greatest common divider between 2 numbers. For example: The greatest common devider between 1071 and 462 is 21.
Python Code.
                        
def euclid(a: int, b: int)->int:
    a, b = min(a,b), max(a, b)
    while True:
        c = a%b
        if c == 0:
            return b
        a = b
        b = c

print(f"{euclid(1071, 462) = }")
                        
                    
.... It prints our answer 21!
#11 (python) Write a function that expects an integer and returns a boolean. It returns True if the given integer is prime, False otherwise. Find the brute force solution first. Is there a more efficient method?
the solution to this problem is quite interesting and presented in the following notebook! Python code Simple brute force Solution
                            
    def is_prime_bad(x: int)->bool:
        for i in range(2, x):
            if x%i == 0:
                return False
        return True
                            
                        
Advanced solution:
                                
from math import sqrt

def is_prime(x: int)->bool:
    for i in range(2, int(sqrt(x))+1):
        if x%i == 0:
            return False
    return True