Fibonacci Java
cetak bilangan fibonacci menggunakan java
public int solution(int N) { int a = 0; int b = 1; int c = 0; while ( a <= N) { System.out.println(a); c = a+b; a = b; b = c; } return a; }
Test Pattern
Some content on this page was disabled on April 1, 2019 as a result of a DMCA takedown notice from Codility Limited. You can learn more about the DMCA here:
Codility Binary Gap
Task :
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.
Write a function:
class Solution { public int solution(int N); }
that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn’t contain a binary gap.
For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation ‘100000’ and thus no binary gaps.
Write an efficient algorithm for the following assumptions:
public int solution(int N) {
// write your code in Java SE 8
char[] bin = Integer.toBinaryString(N).toCharArray();
System.out.println(Integer.toBinaryString(N));
int gap = -1;
int len = 0;
int lim = 0;
char last = 0;
int longGap = 0;
for (int i = 0; i < bin.length; i++) {
if (last != bin[i] && bin[i] == "1".charAt(0) && lim < 2) {
gap++;
lim++;
} else if (bin[i] == "0".charAt(0)) {
len++;
}
last = bin[i];
if (lim == 2) {
lim = 1;
if (len > longGap) {
longGap = len;
}
len = 0;
}
}
return longGap;
}
MFA dengan Google Authenticator
Multi-Factor Authentication (MFA)
MFA digunakan untuk meningkatkan keamanan dari akun kita, biasanya jika kita ingin masuk ke suatu aplikasi maka akan diminta username dan password. Dengan MFA ini maka akan bertambah satu lapis kemananan lagi dengan MFA Code. dan juga MFA ini merupakan fitur keamanan yang direkomendasikan oleh Amazon Web Service (AWS) sendiri.
How It Works
Dengan MFA kita bisa mengasosiasikan Akun kita ke sebuah piranti yaitu Handphone, dengan bantuan Aplikasi Google Authenticator. Aplikasi tersebut akan membuat kode – kode secara acak dengan interval waktu tertentu sehingga anda tidak perlu repot untuk menghafalnya.
Dibawah ini contoh bagaimana cara mengaktifkan MFA untuk akun AWS kita, menggunakan piranti berupa handphone dengan aplikasi Google Authenticator.
- Masuk ke menu IAM (Identity and Access Management)
- Kemudian di bagian Dashboard klik menu Activate MFA
- AWS akan memberi pilihan apakah kita ingin menggunakan virtual MFA device atau hardware MFA device. Dalam contoh ini, perangkat yang akan kita gunakan adalah handphone, dengan bantuan aplikasi. Sehingga kita pilih opsi virtual MFA
- AWS akan menampilkan instruksi untuk virtual MFA, yaitu meminta kita menyiapkan aplikasi yang kompatibel dengan sistem MFA AWS. Dalam contoh ini, kita akan menggunakan aplikasi Google Authenticator.
- AWS akan menampilkan QR code
- Siapkan aplikasi Google Authenticator
- Google Authenticator akan menampilkan angka-angka acak 6 digit yang otomatis berubah secara berkala
- Kembali ke halaman AWS, masukkan dua kode acak yang ditampilkan Google Authenticator secara berurutan. Kemudian, klik pada Activate Virtual MFA.
Selesai. Sekarang setiap kali Anda melakukan login, setelah memasukkan nama akun / email dan password, Anda juga akan diminta memasukkan kode acak yang ditampilkan Google Authenticator di perangkat Anda.
credit to awanreka
Basic Restful API Python 3 on Windows 10
Hello, udah lama ga posting nih, kali ini mau sharing tentang restful API dengan Python. ini hal baru bagi penulis, karena biasa develop restful API dengan java. yuk mari kita mulai bagi yang belum paham atau belum kenal REST itu apa, kenalan dulu yuk dengan REST tak kenal maka tak sayang…. 🙂 , dibawah ini penjelasannya.
REST
Apa itu REST (REpresentational State Transfer) ?
menurut laman TutorialPoints REST itu : REST stands for REpresentational State Transfer. REST is a web standards based architecture and uses HTTP Protocol for data communication. It revolves around resources where every component is a resource and a resource is accessed by a common interface using HTTP standard methods.
jadi kalau tidak salah kesimpulan penulis tentang REST singkatnya sepeti ini, REST Merupakan standard dalam arsitektur web yang menggunakan Protocol HTTP untuk pertukaran data. Rest merupakan salah satu metode dari implementasi Web Services. ada satu metode lain yaitu SOAP (Simple Object Access Protocol). untuk yang ingin tau lebih lanjut silahkan mampir ke TutorialPoints.
sudah kenalan dengan REST kan. sekarang kita masuk ke materinya.
Bahan yang diperlukan :
- Python 3.6.3
- Flask
- Flask-SQLAlchemy
- Flask-Restful
- SQlite3
- Jsonify
Lest get started
Rest punya 4 opsi method
- GET
- PUT
- POST
- DELETE
disini penulis akan menggunakan method GET dulu, method yang lain akan di kerjakan nanti.
sebelum masuk ke code, download terlebih dahulu databasenya disini, kita akan menggunakan SQLite, pembahasan SQLite akan di post nanti. dan extract file bernama chinook.db ke folder project , misalnya ‘python_rest’. setelah download file db, lalu buat file server.py di folder ‘python_rest’
Lalu kita buat virtual environment untuk Python 3.6 setelah install paket2 yang diperlukan lalu di aktifasi.
setelah itu kita coba connect ke database
code:
from flask import Flask, request from flask_restful import Resource, Api from sqlalchemy import create_engine from json import dumps from flask_jsonpify import jsonify db_connect = create_engine('sqlite:///chinook.db') app = Flask(__name__) api = Api(app) class Employees(Resource): def get(self): #connect database conn = db_connect.connect() query = conn.execute("select * from employees;") return {'employees': [i[0] for i in query.cursor]} class Tracks(Resource): def get(self): conn = db_connect.connect() query = conn.execute("select trackid, name, composer, unitprice from tracks;") result = {'data': [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]} return jsonify(result) class Employees_Name(Resource): def get(self, employee_id): conn = db_connect.connect() query = conn.execute("select * from employees where EmployeeId =%d " %int(employee_id)) result = {'data': [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]} return jsonify(result) api.add_resource(Employees, '/employees') # Route_1 api.add_resource(Tracks, '/tracks') # Route_2 api.add_resource(Employees_Name, '/employees/<employee_id>') # Route_3 if __name__ == '__main__': app.run(port=5002)
jalankan dengan perintah berikut:
test setiap link yang dibuat tadi:
sip, REST API dengan Python 3.6 sederhana sudah selesai, mudahkan.
Puzzle String
There is a well-known puzzle called Word Search that involves looking for words in a grid of letters.
The words are given in a list and can appear in the grid horizontally, vertically, or diagonally in any direction.
In this task, you should implement a solver for word search. You will be given grids and a word to search for,
and you have to find how many times that word comes out in the grid. Words that are spelled the same backwards and forwards,
also known as palindromes, will not be given, so you don’t need to worry about words that match in the exact same spot in two different directions.
Input:
The first line is the number of test cases T. Each test case will have two numbers N and M, each on their own line given in that order.
Following that is N lines of M lowercase letters each representing the grid of letters. Lastly, a word W is given that you must look for.
Output:
For each test case, output one line of the form “Case C: X” (without the quotes), where C is the case number (starting from 1),
and X is how many times the word W appeared in the grid.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 100
1 ≤ M ≤ 100
1 ≤ length(W) ≤ 100
Sample Input:
3
3
4
catt
aata
tatc
cat
5
5
gogog
ooooo
godog
ooooo
gogog
dog
2
8
bananana
kalibrrr
nana
Sample Output:
Case 1: 4
Case 2: 8
Case 3: 4
Answer :
int foundRow; int foundColumn; String word; char[][] wordPuzzle; int found = 0; int x[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; int y[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; private void puzzleString() throws IOException{ //readFile("E:\\input.in"); Object[] input = { 3, 3, 4, "catt", "aata", "tatc", "cat", 5, 5, "gogog", "ooooo", "godog", "ooooo", "gogog", "dog", 2, 8, "bananana", "kalibrrr", "nana" }; int T = (Integer) input[0]; int point = 0; int row = 0; for (int i = 1; i <= T; i++) { found = 0; point++; row = (Integer) input[point]; point++; int col = (Integer) input[point]; wordPuzzle = new char[row][col]; for (int j = 0; j < wordPuzzle.length; j++) { point++; wordPuzzle[j] = input[point].toString().toCharArray(); } point++; word = input[point].toString(); for (int r = 0; r < row; r++) { for (int c = 0; c < col; c++) { searchWordPuzzle(wordPuzzle, r, c, word); } } System.out.println("Case "+i+": "+found); } } public static void main(String[] args) throws Exception { PuzzleString p = new PuzzleString(); p.puzzleString(); } void searchWordPuzzle(char grid[][], int row, int col, String word){ if (grid[row][col] != word.charAt(0)) return; int len = word.length(); for (int dir = 0; dir < 8; dir++){ int k, rd = row + x[dir], cd = col + y[dir]; for (k = 1; k < len; k++){ if (rd >= grid.length || rd < 0 || cd >= grid[0].length || cd < 0) break; if (grid[rd][cd] != word.charAt(k)) break; rd += x[dir]; cd += y[dir]; } if (k == len) found++; } return; }
Total Number – Divisible number
public static void main(String[] args) throws ParseException { int[] input = { 3, 4719, 5761, 80, 30, 9907, 10, 5, 9084, 17}; int T = Integer.valueOf(input[0]); int proces = 1; while (T != 0) { for (int i = 1; i = 1 && A <= B && B < 10000) { if (K < 10000) { int totalDiv = (int) Math.floor(B / K); int excludeDivisibles = (int) Math.floor((A - 1) / K); System.out.println("Case " + i + ": " + (totalDiv - excludeDivisibles)); T--; } } } } }
How to loop a Map in Java
How to loop iterate map or hash map in java
Map<String, String> map = new HashMap<String, String>(); map.put("1", "SATU"); map.put("2", "DUA"); map.put("3", "TIGA"); //loop a Map for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue()); } //Java 8 only map.forEach((k,v)->System.out.println("Key : " + k + " Value : " + v));
Test Java
1. A non-empty zero-indexed array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
For example, in array A such that:
A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 A[4] = 9 A[5] = 7 A[6] = 9
- the elements at indexes 0 and 2 have value 9,
- the elements at indexes 1 and 3 have value 3,
- the elements at indexes 4 and 6 have value 9,
- the element at index 5 has value 7 and is unpaired.
Answer:
int x =0; for (int i = 0; i < A.length; i++) { x = x^A[i]; } System.out.println(x);
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.
Write a function:
class Solution { public int solution(int N); }
that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn’t contain a binary gap.
For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5.
Assume that:
- N is an integer within the range [1..2,147,483,647].
Complexity:
- expected worst-case time complexity is O(log(N));
- expected worst-case space complexity is O(1).
Answer:
String n = Integer.toBinaryString(20); int gap =0; int gap2 =0; int d = 0; char[] c =n.toCharArray(); boolean s = false; for (int i = 0; i < c.length; i++) { if(d > 0){ if('0' == c[i]){ gap++; }else{ d = 0; } } if('1' == c[i]){ d = 1; if(gap > gap2){ gap2 = gap; } gap = 0; } } System.out.println(gap2);
3. given a zero-indexed array A consisting of N integers and an integer K, returns the array A rotated K times.
For example, given array A = [3, 8, 9, 7, 6] and K = 3, the function should return [9, 7, 6, 3, 8].
Answer :
int[] A = new int[5]; A[0] = 3; A[1] = 8; A[2] = 9; A[3] = 7; A[4] = 6; int K =3; int[] B = new int[A.length]; for (int i = 0; i < A.length; i++) { System.out.println((i + K ) % A.length); B[(i + K ) % A.length] = A[i]; } System.out.println(B);
Membuat Segitiga Menggunakan JAVA
1. Contoh membuat segitiga seperti dibawah ini
for (int i = 0; i < 4; i++) { for (int j = 0; j <= i; j++) { System.out.print("*"); } System.out.println(""); }
2. Segitiga terbalik
int i, j; int n =4; for (i = n; i >= 1; i--) { for (j = 0; j < n - i; j++){ System.out.print(" "); } for (j = 0; j < 2 * i - 1; j++){ System.out.print("*"); } System.out.println(""); } System.out.println("\n");
3. Segitiga terbalik 2
*****
****
***
**
*
int n = 5; for (int i = 0; i <= n; i++) { for (int j = 0; j < (n - i); j++) { System.out.print(" * "); } for (int x = 0; x < (2 * i - 1); x++) { System.out.print(" "); } System.out.println(""); }
3. Segitiga seperti berikut:
*****
****
***
**
*
int n = 5; for (int i = 0; i <= n; i++) { for (int x = 0; x < i; x++) { System.out.print(" "); } for (int j = 0; j < (n - i); j++) { System.out.print("*"); } System.out.println(""); }