Java – KenKen Puzzle Solver

import java.util.HashMap;

public class KenKen {

    static int[][] table;//2-dimensional array to represent matrix
    static int width = 4;//this means 4x4 table

    // this hashmap stores contraints like 16x, 7+, 2-, 4
    static HashMap<String, String> constraints = new HashMap<>();

    public static void main(String[] args) {

        table = getEmptyTable();
        fillConstraints();

        int r = 0;//row index
        int c = 0;//column index

        // check all combinations while row index and column index not more than index
        while (r<width && c<width) {
            if (table[r][c] < width) {// if cell value less than max value
                table[r][c]++; // increment cell value by 1
                if (isValid(r, c)) { // check cell value
                    c++; // if cell value is valid move to next cell
                    if (c == width) {//if there is no more column, move to
                        c = 0;//first column
                        r++;//of next line
                    }
                }
            } else {//if cell value more than max value
                table[r][c] = 0;//make it 0
                c--;//because we move to previous column
                if (c < 0) {//if there is no column on the left, move to
                    c = width - 1;//the last column
                    r--;//of previous row
                }
            }
        }
       
        printTable();//print result

    }
   
    // kenken constraints
    private static void fillConstraints() {
        constraints.put("0-0 0-1 1-1", "16 *"); //cell(row:0,column:0) * cell(row:0,column:1) * cell(row:1,column:1) = 16
        constraints.put("0-2 0-3 1-2", "7 +"); // cell(row:0,column:2) + cell(row:0,column:3) + cell(row:1,column:2) = 7
        constraints.put("1-0 2-0", "2 -"); // cell(row:1,column:0) - cell(row:2,column:0) = 2
        constraints.put("2-1 3-0 3-1", "12 *"); // cell(row:2,column:1) * cell(row:3,column:0) * cell(row:3,column:1) = 12
        constraints.put("2-2 2-3", "2 /"); // cell(row:2,column:2) / cell(row:2,column:3) = 2
        constraints.put("3-2 3-3", "2 /"); // cell(row:3,column:2) / cell(row:3,column:3) = 2
        constraints.put("1-3", "4 ="); // cell(row:1,column:3) = 4
    }


    private static boolean isValid(int r, int c) {
        // this method checks cell value validity by its row index and column index

        // check row validity
        for (int i = 0; i < width; i++) {
            if (i != c && table[r][c] == table[r][i])
                return false;
        }

        // check column validity
        for (int i = 0; i < width; i++) {
            if (i != r && table[r][c] == table[i][c])
                return false;
        }

        // check constraints validity
        for (String key : constraints.keySet()) { // loop each key(cell positions)
           
            if (key.contains(r + "-" + c)) {
                //if key(cell positions) has needed position

                String constraint = constraints.get(key); // get contraint like "16 *" which means multiply of cells equals 16

                String operator = constraint.substring(constraint.indexOf(" ") + 1);//get operator. eg "*" from "16 *"
                int num = Integer.parseInt(constraint.substring(0, constraint.indexOf(" ")));//get number. eg 16 from "16 *"
                double result = 0;//using this variable we will check contstraint

                String[] positions = key.split(" ");//split cell positions "0-0 0-1 1-1" to "0-0","0-1","1-1"
                for (int i = 0; i < positions.length; i++) {
                    // loop each position like "0-0" from "0-0 0-1 1-1"
                   
                    int posR = Integer.parseInt(positions[i].substring(0, positions[i].indexOf("-"))); //get row. eg 1 from "1-2"
                    int posC = Integer.parseInt(positions[i].substring(positions[i].indexOf("-") + 1)); //get column eg 2 from "1-2"
                   
                    if (table[posR][posC] == 0) return true;//if cell value equals 0, we cannot make sure this is valid or not, so return true which means valid

                    if (operator.equals("="))
                        return (table[posR][posC] == num);//if constraint "=", let's check equality of cell value and constraint number
                    else if (operator.equals("+"))
                        result = result + table[posR][posC];//if "+", add cell value to sum, in order to compare it in the end of check
                    else if (operator.equals("*")) {
                        if (result == 0)
                            result = 1;// if multiplication of 0 is 0, that's why let's start with 1
                        result = result * table[posR][posC];//multiply result by cell value
                    } else if (operator.equals("-")) {
                        result = result - table[posR][posC];//minus cell value from another value
                        if (result < 0)
                            result = result * -1;//if result is negative, make it positive :)
                    } else if (operator.equals("/")) {
                        if (result == 0) {
                            result = 1;// same as multiplication, 0/x=0
                        } else {
                            if (result % table[posR][posC] != 0 && table[posR][posC] % result != 0)
                                return false;// if we cannot devide value by cell value, it is not divisible (not valid)
                        }
                        result = result / table[posR][posC];//devide one value by another
                        if (result < 1) {// image we have 2 and 4. 2/4=0.5 so we convert this to 1/0.5=2 like 4/2=2
                            result = 1 / result;
                        }

                    }

                }

                return result == num;//check constraint value
                // for example c1=2, c2=4, c3=2
                // contraint "16 *"
                // c1 * c2 * c3 = 16
                // 2 * 4 * 2 = 16 valid

            }
        }

        return true;

    }

   
   
    /*
        method to get empty matrix table with 0s
        0 means empty
        if width = 3;
        matrix will look like this:
        0 0 0
        0 0 0
        0 0 0
     */

    private static int[][] getEmptyTable() {
        int[][] table = new int[width][];

        for (int i = 0; i < width; i++) {
            table[i] = new int[width];
            for (int num : table[i]) {
                num = 0;
            }
        }
        return table;
    }
   
   
   
   
    // print table on console
    private static void printTable() {
       
        for (int i = 0; i < table.length; i++) {
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < width; j++) {
                if (sb.toString().length() > 0)
                    sb.append(" ");
                sb.append(table[i][j]);
            }
            System.out.println(sb.toString());
        }

    }
   
   

}

Java – Monty Hall problem prove

Wikipedia: Suppose you’re on a game show, and you’re given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what’s behind the doors, opens another door, say No. 3, which has a goat. He then says to you, “Do you want to pick door No. 2?” Is it to your advantage to switch your choice?

Vos Savant’s response was that the contestant should switch to the other door (vos Savant 1990a). Under the standard assumptions, contestants who switch have a 2/3 chance of winning the car, while contestants who stick to their initial choice have only a 1/3 chance.

Using Java, I tested this problem for 10000 times and I found that wins percentage is 33% when player does not change their decision after host opened one of door without car. If player changes decision, wins percentage is 66% which is double comparing to if player does not change.

Continue reading Java – Monty Hall problem prove

Android – write and read file to/from internal storage

                try {
                    FileOutputStream outputStream = getActivity().openFileOutput(filename, Context.MODE_PRIVATE);
                    outputStream.write(result.getBytes());
                    outputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                try {
                    FileInputStream inputStream = openFileInput(filename);
                    BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
                    StringBuilder total = new StringBuilder();
                    String line;
                    while ((line = r.readLine()) != null) {
                        total.append(line);
                    }
                    r.close();
                    inputStream.close();
                    Log.d("File", "File contents: " + total);
                } catch (Exception e) {
                    e.printStackTrace();
                }

Hackerrank STDIN template

        ArrayList<String> lines = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            lines.add(scanner.nextLine());
        }
        scanner.close();
       
        String[] input = new String[lines.size()];
        for (int i = 0; i < lines.size(); i++) {
            input[i]=lines.get(i);
        }

Programming languages rating

Jul 2016 Jul 2015 Change Programming Language Ratings Change
1 1 Java 19.804% +2.08%
2 2 C 12.238% -3.91%
3 3 C++ 6.311% -2.33%
4 5 change Python 4.166% -0.09%
5 4 change C# 3.920% -1.73%
6 7 change PHP 3.272% +0.38%
7 9 change JavaScript 2.643% +0.45%
8 8 Visual Basic .NET 2.517% +0.09%
9 11 change Perl 2.428% +0.62%
10 12 change Assembly language 2.281% +0.75%
11 15 change Ruby 2.122% +0.74%
12 13 change Delphi/Object Pascal 2.045% +0.57%
13 10 change Visual Basic 2.012% +0.07%
14 16 change Swift 1.960% +0.73%
15 6 change Objective-C 1.881% -1.46%
16 19 change MATLAB 1.558% +0.35%
17 17 R 1.514% +0.28%
18 18 PL/SQL 1.456% +0.24%
19 22 change COBOL 1.135% +0.10%
20 39 change Groovy 1.125% +0.80%

Source: TIOBE Index

Java – How to convert a string into a GZIP Base64 string? and reversaly?

In this post, I want to show how to convert human readible String to gzipped base64 String and reversaly.

GzipUtil.java

package com.gayratrakhimov.gzipsandbox;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipUtil {

    public static byte[] compress(String string) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream(string.length());
        GZIPOutputStream gos = new GZIPOutputStream(os);
        gos.write(string.getBytes());
        gos.close();
        byte[] compressed = os.toByteArray();
        os.close();
        return compressed;
    }

    public static String decompress(byte[] compressed) throws IOException {
        final int BUFFER_SIZE = 32;
        ByteArrayInputStream is = new ByteArrayInputStream(compressed);
        GZIPInputStream gis = new GZIPInputStream(is, BUFFER_SIZE);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] data = new byte[BUFFER_SIZE];
        int bytesRead;
        while ((bytesRead = gis.read(data)) != -1) {
            baos.write(data, 0, bytesRead);
        }
        gis.close();
        return baos.toString("UTF-8");
    }

}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        encode();
        decode();

    }

    // String(human readible)->compress as gzip->String(base64 format)
    private void encode(){

        try {
            String textToEncode = "Hello";
            byte[] compressed = GzipUtil.compress(textToEncode);
            String result = Base64.encodeToString(compressed, Base64.DEFAULT);
            Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //String(base64 format)->decompress zip->String(human readible)
    private void decode(){

        try {
            String textToDecode = "H4sIAAAAAAAAAPNIzcnJBwCCidH3BQAAAA==\n";
            byte[] data = Base64.decode(textToDecode, Base64.DEFAULT);
            String result = GzipUtil.decompress(data);
            Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
   
}

Java – How to generate MD5 hash from String

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {

    public static void main(String[] args) {
       
        System.out.println(md5a("password"));//5f4dcc3b5aa765d61d8327deb882cf99
        System.out.println(md5b("password"));//5f4dcc3b5aa765d61d8327deb882cf99
       
    }
   
    // method 1
    private static String md5a(String password){

        byte[] bytes = getBytes(password);

        // convert the byte to hex format method 1
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
        }
       
        return sb.toString();
       
    }

    // method 2
    private static String md5b(String password){
       
        byte[] bytes = getBytes(password);

        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xff & bytes[i]);
            if (hex.length() == 1)
                hexString.append('0');
            hexString.append(hex);
        }

        return hexString.toString();
       
    }
   
    private static byte[] getBytes(String password) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        md.update(password.getBytes());
        byte byteData[] = md.digest();
        return byteData;
    }

}