file_id
int64 1
250k
| content
stringlengths 0
562k
| repo
stringlengths 6
115
| path
stringlengths 1
147
|
---|---|---|---|
735 | package com.zhy.utils;
import android.content.Context;
import android.widget.Toast;
/**
* Toast统一工具类
*
*
*/
public class T {
private T() {
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
public static boolean isShow = true;
/**
* 短时间显示Toast
*
* @param context
* @param message
*/
public static void showShort(Context context, CharSequence message) {
if (isShow)
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
/**
* 短时间显示Toast
*
* @param context
* @param message
*/
public static void showShort(Context context, int message) {
if (isShow)
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
/**
* 长时间显示Toast
*
* @param context
* @param message
*/
public static void showLong(Context context, CharSequence message) {
if (isShow)
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
/**
* 长时间显示Toast
*
* @param context
* @param message
*/
public static void showLong(Context context, int message) {
if (isShow)
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
/**
* 自定义显示Toast时间
*
* @param context
* @param message
* @param duration
*/
public static void show(Context context, CharSequence message, int duration) {
if (isShow)
Toast.makeText(context, message, duration).show();
}
/**
* 自定义显示Toast时间
*
* @param context
* @param message
* @param duration
*/
public static void show(Context context, int message, int duration) {
if (isShow)
Toast.makeText(context, message, duration).show();
}
} | wswenyue/AndroidUtils | T.java |
744 | public class Sudoku {
public static void main(String[] args) {
char[][] board = { { '5', '3', '.', '.', '7', '.', '.', '.', '.' },
{ '6', '.', '.', '1', '9', '5', '.', '.', '.' }, { '.', '9', '8', '.', '.', '.', '.', '6', '.' },
{ '8', '.', '.', '.', '6', '.', '.', '.', '3' }, { '4', '.', '.', '8', '.', '3', '.', '.', '1' },
{ '7', '.', '.', '.', '2', '.', '.', '.', '6' }, { '.', '6', '.', '.', '.', '.', '2', '8', '.' },
{ '.', '.', '.', '4', '1', '9', '.', '.', '5' }, { '.', '.', '.', '.', '8', '.', '.', '7', '9' } };
solve(0, 0, board);
}
public static void solve(int r, int c, char[][] board) {
if (c == 9) {
c = 0;
r++;
}
if (r == 9) {
print(board);
System.out.println("===============");
return;
}
if (board[r][c] != '.') {
solve(r, c + 1, board);
} else {
for (int i = 1; i <= board.length; i++) {
if (isSafe(r, c, i, board)) {
board[r][c] = (char) ('0' + i);
solve(r, c + 1, board);
}
board[r][c] = '.';
}
}
}
public static boolean isSafe(int r, int c, int i, char[][] board) {
char ch = (char) ('0' + i);
for (int R = 0; R < 9; R++) {
if (board[R][c] == ch) {
return false;
}
}
for (int C = 0; C < 9; C++) {
if (board[r][C] == ch) {
return false;
}
}
int box_r = r / 3;
int box_c = c / 3;
for (int R = box_r * 3; R < box_r * 3 + 3; R++) {
for (int C = box_c * 3; C < box_c * 3 + 3; C++) {
if (board[R][C] == ch) {
return false;
}
}
}
return true;
}
public static void print(char[][] board) {
for (char[] row : board) {
for (char b : row) {
System.out.print(b + " ");
}
System.out.println();
}
}
}
| satyam2k3/Hacktober-Fest-2022 | Sudoku |
746 | class Solution {
public String longestPalindrome(String str) {
int maxLengthPalindrome = 0;
if (str.length() == 0) {
return "";
}
String result = "";
// for (int i = 0; i < n; i++) {
// for (int j = i + 1; j <= n; j++) {
// //System.out.println(str.substring(i, j));
// if (maxLengthPalindrome < (j - i) && istPalindrom(str.substring(i, j).toCharArray())) {
// maxLengthPalindrome = j - i;
// result = str.substring(i, j);
// }
// }
// }
//int aga = 1;
int targetTimes = 1;
for (int i = str.length(); i >= 0; i--) {
for (int times = 0; times < targetTimes; times++) {
//System.out.println(aga + " " + times + " " + i + " " + str.substring(times, times + i));
//aga++;
if (istPalindrom(str.substring(times, times + i).toCharArray())) {
return str.substring(times, times + i);
}
}
targetTimes++;
}
return "";
}
public boolean istPalindrom(char[] word) {
int i1 = 0;
int i2 = word.length - 1;
while (i2 > i1) {
if (word[i1] != word[i2]) {
return false;
}
++i1;
--i2;
}
return true;
}
} | bbohosyan/LeetCode | 5.java |
747 | //{ Driver Code Starts
import java.io.*;
import java.util.*;
public class GFG {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int testcases = Integer.parseInt(br.readLine());
while (testcases-- > 0) {
int n = Integer.parseInt(br.readLine());
String line1 = br.readLine();
String[] a1 = line1.trim().split("\\s+");
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(a1[i]);
}
Solution ob = new Solution();
int ans=ob.minNumber(a,n);
System.out.println(ans);
}
}
}
// } Driver Code Ends
//User function Template for Java
class Solution {
public int minNumber(int arr[], int N) {
// Calculate the sum of the array
int sum = 0;
for (int num : arr) {
sum += num;
}
// Check if the sum is prime
if (isPrime(sum)) {
return 0; // Sum is already prime, no need to add any number
}
// Find the smallest positive number to make the sum prime
int diff = 0;
while (!isPrime(sum + diff)) {
diff++;
}
return diff;
}
// Helper function to check if a number is prime
private boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
| dhruvabhat24/Geeks-For-Geeks-December | 8.java |
748 | package algorithms_project;
class M {
public final String value;
public boolean isVisited;
public M parent;
public Road[] next_states;
public double heuristic;
public M(String val,double heuristic1) {
value = val;
heuristic=heuristic1;
}
@Override
public String toString() {
return value;
}
double set_h(){
return heuristic;
}
public void isVisited(boolean isVisited) {
this.isVisited = isVisited;
}
void equal() {
}
}
| kinanabuasi/Find_the_student_best_way_Project | M.java |
749 | class Cpu {
int price;
Cpu(int p) {
this.price = p;
}
class Processor {
int cores;
String manufacture;
Processor(int n, String m) {
this.cores = n;
this.manufacture = m;
}
void display() {
System.out.println("No of Cores : " + this.cores);
System.out.println("Processor manufactures : " + this.manufacture);
}
}
static class Ram {
int memory;
String manufacture;
Ram(int n, String m) {
this.memory = n;
this.manufacture = m;
}
void display() {
System.out.println("Memory Size : " + this.memory);
System.out.println("Memory manufactures : " + this.manufacture);
}
}
void display() {
System.out.println("Price of CPU : " + this.price);
}
public static void main(String[] args) {
Cpu intel = new Cpu(23000);
Cpu.Processor i_processor = intel.new Processor(4, "intel");
Cpu.Ram i_ram = new Ram(1024, "Asus");
intel.display();
i_processor.display();
i_ram.display();
}
}
| techworldthink/MCA-LAB-APJ-Abdul-Kalam-Technological-University-2020-Present | S2-LAB/OOPS_LAB_JAVA_MCA/CYCLE 1/cpu.java |
756 | class Solution {
int m;
int n;
int peri;
void dfs(int[][] grid, int i, int j) {
if(i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) {
peri++;
return;
}
if(grid[i][j] == -1) {
return;
}
grid[i][j] = -1; // mark visited
dfs(grid, i+1, j);
dfs(grid, i-1, j);
dfs(grid, i, j+1);
dfs(grid, i, j-1);
}
int islandPerimeter(int[][] grid) {
m = grid.length;
n = grid[0].length;
peri = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(grid[i][j] == 1) {
dfs(grid, i, j);
return peri;
}
}
}
return -1;
}
}
| Biswajit6997/LeetCode-Problems | a.txt |
757 | import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
import static org.antlr.v4.runtime.CharStreams.fromFileName;
public class V {
public static void main(String[] args) {
try {
CharStream input = fromFileName("main.v");
VLexer lexer = new VLexer(input);
TokenStream tokens = new CommonTokenStream(lexer);
VParser parser = new VParser(tokens);
VListener listener = new VListener();
ParseTree tree = parser.program();
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(listener, tree);
} catch (Exception e) {
e.printStackTrace();
}
}
public static class VListener extends VBaseListener {
private int scope = 0;
public void printScope() {
this.printScope("");
}
public void printScope(String text) {
for (int i = 0; i < scope; i++) {
text += "\t";
}
System.out.print(text);
}
@Override
public void enterProgram(VParser.ProgramContext ctx) {
System.out.println("\t\tSymbolTable\n");
}
@Override
public void enterDeclaration(VParser.DeclarationContext ctx) {
this.printScope(String.format("(at line %s)\t", ctx.start.getLine()));
System.out.print("GlobalVariable ");
}
@Override
public void exitDeclaration(VParser.DeclarationContext ctx) {
System.out.println("");
}
@Override
public void enterFunction(VParser.FunctionContext ctx) {
this.printScope(String.format("\n(at line %s)\t", ctx.start.getLine()));
String functionName = ctx.ID().getText();
String returnType = ctx.basicType().getText();
String text = String.format("Function (name: %s, returnType: %s, parameters: (", functionName, returnType);
System.out.print(text);
scope++;
}
@Override
public void exitFunction(VParser.FunctionContext ctx) {
scope--;
this.printScope();
System.out.print("\t\t}\n\n");
}
@Override
public void enterParameterList(VParser.ParameterListContext ctx) {
if (ctx.variableList() == null) {
System.out.print("none");
}
}
@Override
public void exitParameterList(VParser.ParameterListContext ctx) {
System.out.println(")) {");
}
@Override
public void enterVariableList(VParser.VariableListContext ctx) {
var variableNames = ctx.ID();
var variableTypes = ctx.type();
for (int i = 0; i < variableNames.size(); i++) {
String variableName = variableNames.get(i).getText();
String variableType = variableTypes.get(i).basicType().getText();
String text = String.format("(name: %s, type: %s)", variableName, variableType);
if (i < variableNames.size() - 1) {
text += ", ";
}
System.out.print(text);
}
}
@Override
public void enterDeclarationInFunction(VParser.DeclarationInFunctionContext ctx) {
this.printScope(String.format("(at line %s)\t", ctx.start.getLine()));
System.out.print("LocalVariable ");
}
@Override
public void exitDeclarationInFunction(VParser.DeclarationInFunctionContext ctx) {
System.out.println("");
}
}
}
| oznakn/metu-hw | ceng444/vlang-antlr/V.java |
758 | package Project;
import Basic.regis;
import java.sql.*;
class k {
private static final String url = "jdbc:mysql://localhost";
private static final String user = "root";
private static final String password = "test";
Connection con;
Statement stmt;
int result;
ResultSet rs;
public void con() {
try {
con = DriverManager.getConnection(url, user, password);
System.out.println("Success");
stmt = con.createStatement();
String sql = "use ak";
stmt.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
}
}
public void res(String a,String b)
{
try{
// stmt = con.createStatement();
String sql = "insert into user values('"+a+"','"+b+"','0')";
stmt.executeUpdate(sql);
}
catch (Exception e) {
e.printStackTrace();
}
}
public int log(String a,String b)
{
try{
stmt = con.createStatement();
String sql = "select COUNT(*) as v from user where name='"+a+"' AND password='"+b+"'";
rs= stmt.executeQuery(sql);
rs.next();
int t=rs.getInt("v");
return t;
}
catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public int log(String a,String b,int t)
{
try{
stmt=con.createStatement();
String sql="select COUNT(*) as v from admin where name='"+a+"'AND password='"+b+"'";
rs=stmt.executeQuery(sql);
rs.next();
int p=rs.getInt("v");
return p;
}
catch(Exception e){
e.printStackTrace();
return 0;
}
}
public void que(String a,String b)
{
try{
// stmt = con.createStatement();
String sql = "insert into question values('"+a+"','"+b+"')";
stmt.executeUpdate(sql);
}
catch (Exception e) {
e.printStackTrace();
}
}
public void que1(String a)
{
try{
// stmt = con.createStatement();
String sql = "insert into question2 values('"+a+"')";
stmt.executeUpdate(sql);
}
catch (Exception e) {
e.printStackTrace();
}
}
public void disp()
{
try{
String so;
stmt=con.createStatement();
String sql="select * from question2 ";
rs=stmt.executeQuery(sql);
while(rs.next())
{
so=rs.getString("name");
System.out.println(so);
}
}
catch(Exception e){
e.printStackTrace();
}
}
public void display()
{
try{
String so;
stmt=con.createStatement();
String sql="select * from question ";
rs=stmt.executeQuery(sql);
while(rs.next())
{
so=rs.getString("path");
System.out.println(so);
}
}
catch(Exception e){
e.printStackTrace();
}
}
public void score(String a,String b,int c)
{
try{
String sql = "update user set score=score+'"+c+"' where name='"+a+"' AND password='"+b+"'";
stmt.executeUpdate(sql);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
| Gourav2906/Codex | k.java |
760 | import java.util.Scanner;
public class DijkstrasAlgorithm {
public static int path[] = new int[10];
public static void main(String[] args) {
int tot_nodes, i, j;
int cost[][] = new int[10][10];
int dist[] = new int[10];
int s[] = new int[10];
System.out.println("\n\t\t-------Creation of Graph-----");
System.out.println("\nEnter Total Number of Nodes:");
Scanner in = new Scanner(System.in);
tot_nodes = in.nextInt();
createGraph(tot_nodes, cost);
for (i = 0; i < tot_nodes; i++) {
System.out.println("\n\t\tPress any Key To Continue...");
System.out.println("\n\t\tWhen Source=" + i);
for (j = 0; j < tot_nodes; j++) {
Dijkstra(tot_nodes, cost, i, dist);
if (dist[j] == 999)
System.out.println("\n There is no Path to " + j);
else {
displayPath(i, j, dist);
}
}
}
}
public static void createGraph(int tot_nodes, int cost[][]) {
int i, j, val, tot_edges, count = 0;
for (i = 0; i < tot_nodes; i++) {
for (j = 0; j < tot_nodes; j++) {
if (i == j)
cost[i][j] = 0;
else
cost[i][j] = 999;
}
}
System.out.println("\n Total Number of Edges:");
Scanner in = new Scanner(System.in);
tot_edges = in.nextInt();
while (count < tot_edges) {
System.out.println("\nEnter Vi and Vj:");
i = in.nextInt();
j = in.nextInt();
System.out.println("\nEnter the cost along this edge:");
val = in.nextInt();
cost[j][i] = val;
cost[i][j] = val;
count++;
}
}
public static void Dijkstra(int tot_nodes, int cost[][], int source, int dist[]) {
int i, j, v1, v2, min_dist;
int s[] = new int[10];
for (i = 0; i < tot_nodes; i++) {
dist[i] = cost[source][i];
s[i] = 0;
path[i] = source;
}
s[source] = 1;
for (i = 1; i < tot_nodes; i++) {
min_dist = 999;
v1 = -1;
for (j = 0; j < tot_nodes; j++) {
if (s[j] == 0) {
if (dist[j] < min_dist) {
min_dist = dist[j];
v1 = j;
}
}
}
s[v1] = 1;
for (v2 = 0; v2 < tot_nodes; v2++) {
if (s[v2] == 0) {
if (dist[v1] + cost[v1][v2] < dist[v2]) {
dist[v2] = dist[v1] + cost[v1][v2];
path[v2] = v1;
}
}
}
}
}
public static void displayPath(int source, int destination, int dist[]) {
int i;
System.out.println("\n Step By Step Shortest Path is...\n");
for (i = destination; i != source; i = path[i]) {
System.out.print(i + "<-");
}
System.out.print(source);
System.out.println("\nThe Length = " + dist[destination]);
}
}
| 0dayhunter/java | 5.java |
761 | package com.example.myapplicationteste;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private ListView listLocais;
private String[] itens = {
"Filosofia","Geografia",
"Sociologia", "Quimica",
"Programação Orientada a Objetos", "Historia", "Fisica",
"Biologia", "TCC", "Programação a Internet", "Inglês",
"Topicos Especias em Informatica", "Português","Matematica", "Redes de Computadores"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listLocais = findViewById(R.id.listlocais);
//Criar adaptador para a Lista
ArrayAdapter<String> adaptador = new ArrayAdapter<String>(
getApplicationContext(),
android.R.layout.simple_list_item_1,//layout da lista
android.R.id.text1,//id do layout
itens // a lista a ser passada
);
// Adicionar adaptador para a Lista
listLocais.setAdapter(adaptador);
//Adiciona clique na lista
listLocais.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String valorSelecionado = listLocais.getItemAtPosition(i).toString();
dialog(view , valorSelecionado);
}
public void dialog(View view, String valorSelecionado){
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
//configurar titulo e mensage
dialog.setMessage("Deseja Matricular-se nessa matéria?");
//configurar cancelamento do alert dialog
dialog.setCancelable(false);
//configurar icone
dialog.setIcon(android.R.drawable.ic_btn_speak_now);
//configurar açoes para sim e nâo
dialog.setPositiveButton("sim", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"A matricula na disciplina " + valorSelecionado + " foi realizada", Toast.LENGTH_SHORT).show();
}
});
dialog.setNegativeButton("nao", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Executar a", Toast.LENGTH_SHORT).show();
}
});
dialog.create();
dialog.show();
}
});
}
}
| umthiago/TopicosEspeciaisINF | a.java |
767 | public class B {
public static void main(String[] args) {
System.out.println("Hello world");
int x =10;
System.out.println("answer is :"+x);
}
}
| PasinduUkwatta/Java-Practise-Coding | B.java |
768 | import java.util.*;
class r{
public static void main(String[] args)
{
String original; // Objects of String class
StringBuilder reverse = new StringBuilder();
Scanner in = new Scanner(System.in);
System.out.println("Enter a string/number to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse.append(original.charAt(i));
if (original.equals(reverse.toString()))
System.out.println("Entered string/number is a palindrome.");
else
System.out.println("Entered string/number isn't a palindrome.");
}
} | anirbang324/java-programs | r.java |
770 | /*create or replace procedure add12(i in number,j in number,k out number) is
begin
k:=i+j;
end;*/
import java.sql.*;
class a
{
public static void main(String h[])throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","1234");
CallableStatement ps=con.prepareCall("call add12(?,?,?)");
ps.setInt(1,10);
ps.setInt(2,20);
ps.registerOutParameter(3,Types.INTEGER);
ps.execute();
int n=ps.getInt(3);
System.out.println(n);
}}
| sandipmohapatra/157java | a.java |
771 | import java.util.*;
class Area{
public float returnArea(float l,float b)
{
return l*b;
}
}
public class Main{
public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
Area ob = new Area();
System.out.println("Enter the length and breadth");
float l = sc.nextFloat();
float b = sc.nextFloat();
float area = ob.returnArea(l,b);
System.out.println("Area of rectangle is "+area);
}
} | Welding-Torch/Java-Prac | 2.java |
772 | /*
The design principle used in the provided code is the Single Responsibility
Principle(SRP).
The Single Responsibility Principle states that a class should have only
one reason to change. Each class should encapsulate only one responsibility
or aspect of the program's functionality.
Each class encapsulates and manages its own distinct responsibility
without being concerned with other unrelated tasks. This adherence to the
Single Responsibility Principle improves maintainability, readability, and
flexibility of the codebase.
*/
class Employee {
private String name;
private double hourlyRate;
private int hoursWorked;
public Employee (String name, double hourlyRate, int hoursWorked){
this.name = name;
this.hourlyRate = hourlyRate;
this.hoursWorked = hoursWorked;
}
public double calculatePay(){
/* calculates Pay of an Enployee */
return hourlyRate * hoursWorked;
}
public String getName() {
return name;
}
public double getHourlyRate() {
return hourlyRate;
}
public int getHoursWorked() {
return hoursWorked;
}
}
class EmployeeRepository {
public void saveEmployee(Employee employee) {
/* Saves details of employee in Database */
System.out.println("Saving employee: "+employee.getName());
System.out.println("Hourly rate: Rs. "+employee.getHourlyRate());
System.out.println("Hours worked: "+employee.getHoursWorked());
System.out.println("Total pay: Rs. "+employee.calculatePay());
System.out.println("Employee details saved successfully.\n");
}
}
public class S {
public static void main (String args[]){
Employee employee1 = new Employee("Lakhan Gurjar", 500, 9);
EmployeeRepository repository = new EmployeeRepository();
repository.saveEmployee(employee1);
}
}
| Lakhan-Gurjar/SOLID-Design-Principles | S.java |
773 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class E here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class U extends Mover
{
private int geld = 50;
/**
* Act - do whatever the E wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
for (Actor hero : getObjectsInRange(200, Hero.class))
{
if (Greenfoot.mouseClicked(this))
{
Hero h = (Hero)hero;
h.geefPunt(geld);
h.geefu("U");
Greenfoot.playSound("Sonic Ring sound Effect in stereo.mp3");
getWorld().removeObject(this);
}
}
applyVelocity();
}
}
| ROCMondriaanTIN/project-greenfoot-game-MarekBeers | U.java |
774 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class S here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class S extends Mover
{
private int geld = 50;
int level;
String s = "S";
public S(int level)
{
this.level = level;
}
/**
* Act - do whatever the E wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
for (Actor hero : getObjectsInRange(200, Hero.class))
{
if (Greenfoot.mouseClicked(this))
{
Hero h = (Hero)hero;
h.geefPunt(geld);
h.geefs(s);
Greenfoot.playSound("Sonic Ring sound Effect in stereo.mp3");
getWorld().removeObject(this);
}
}
applyVelocity();
}
}
| ROCMondriaanTIN/project-greenfoot-game-MarekBeers | S.java |
775 | class A {
void exp() {
System.out.println("A is the class");
}
}
class B extends A {
void bexp() {
System.out.println("B is the class ");
}
}
class C extends A{
void me() {
System.out.println("C is the class");
}
}
public class M{
public static void main(String[] args) {
A a= new A();
a.exp();
B b = new B();
b.bexp();
C c = new C();
c.me();
;
}
} | reallywasi/The-OOPs- | M.java |
776 | public class C {
public static void main(String[] args) {
method1();
}
public void method1() {
method2();
}
public static void method2() {
System.out.println("What is radius " + c.getRadius());
}
Circle c = new Circle();
}
| anusornc/week8 | B.java |
777 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class O here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class O extends Mover
{
private int geld = 50;
/**
* Act - do whatever the E wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
for (Actor hero : getObjectsInRange(200, Hero.class))
{
if (Greenfoot.mouseClicked(this))
{
Hero h = (Hero)hero;
h.geefPunt(geld);
h.geefo("O");
Greenfoot.playSound("Sonic Ring sound Effect in stereo.mp3");
getWorld().removeObject(this);
}
}
applyVelocity();
}
}
| ROCMondriaanTIN/project-greenfoot-game-MarekBeers | O.java |
778 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class R here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class N extends Mover
{
private int geld = 50;
String N = "N";
/**
* Act - do whatever the E wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
for (Actor hero : getObjectsInRange(200, Hero.class))
{
if (Greenfoot.mouseClicked(this))
{
Hero h = (Hero)hero;
h.geefPunt(geld);
h.geefn(N);
Greenfoot.playSound("Sonic Ring sound Effect in stereo.mp3");
getWorld().removeObject(this);
}
}
applyVelocity();
}
}
| ROCMondriaanTIN/project-greenfoot-game-MarekBeers | N.java |
779 | import java.util.*;
class Rectangle{
float length;
float breadth;
Rectangle()
{
length=0;
breadth=0;
}
Rectangle(float l,float b)
{
length=l;
breadth=b;
}
Rectangle(float l)
{
length=l;
breadth=l;
}
public float area()
{
return length*breadth;
}
}
public class Main{
public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
Rectangle ob = new Rectangle();
System.out.println("The area of rectangle is "+ob.area());
System.out.println("Enter the length and breadth");
float l= sc.nextFloat();
float b= sc.nextFloat();
Rectangle ob1 = new Rectangle(l,b);
System.out.println("The area of rectangle is "+ob1.area());
System.out.println("Enter the side of Square");
float s= sc.nextFloat();
Rectangle ob2 = new Rectangle(s);
System.out.println("The area of square is "+ob2.area());
}
}
| Welding-Torch/Java-Prac | 5.java |
781 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class E here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class D extends Mover
{
private int geld = 50;
/**
* Act - do whatever the E wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
for (Actor hero : getObjectsInRange(200, Hero.class))
{
if (Greenfoot.mouseClicked(this))
{
Hero h = (Hero)hero;
h.geefPunt(geld);
h.geefd("D");
Greenfoot.playSound("Sonic Ring sound Effect in stereo.mp3");
getWorld().removeObject(this);
}
}
applyVelocity();
}
}
| ROCMondriaanTIN/project-greenfoot-game-MarekBeers | D.java |
782 | import java.util.*;
class Area{
float length;
float breadth;
void calarea()
{
length=0;
breadth=0;
}
void calarea(float l,float b)
{
System.out.println("The area of rectangle is "+(l*b));
}
void calarea(float l)
{
System.out.println("The area of square is "+(l*l));
}
}
public class Main{
public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
Area ob = new Area();
System.out.println("Enter the length and breadth of the rectangle");
float l= sc.nextFloat();
float b= sc.nextFloat();
ob.calarea(l,b);
System.out.println("Enter the side of Square");
float s= sc.nextFloat();
ob.calarea(s);
}
} | Welding-Torch/Java-Prac | 6.java |
784 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Key here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Key extends Actor
{
/**
* Act - do whatever the Key wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
// Add your action code here.
}
}
| ROCMondriaanTIN/project-greenfoot-game-DarkSoul2002 | Key.java |
785 | // BFS algorithm in Java
import java.util.*;
public class Graph {
private int V;
private LinkedList<Integer> adj[];
// Create a graph
Graph(int v) {
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}
// Add edges to the graph
void addEdge(int v, int w) {
adj[v].add(w);
}
// BFS algorithm
void BFS(int s) {
boolean visited[] = new boolean[V];
LinkedList<Integer> queue = new LinkedList();
visited[s] = true;
queue.add(s);
while (queue.size() != 0) {
s = queue.poll();
System.out.print(s + " ");
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n]) {
visited[n] = true;
queue.add(n);
}
}
}
}
public static void main(String args[]) {
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
System.out.println("Following is Breadth First Traversal " + "(starting from vertex 2)");
g.BFS(2);
}
}
| ShriyanshiSrivastava/Data_Structures_For_Hacktoberfest | Hacktoberfest2021/BfsAlgorithm/BFS.java |
786 |
import android.util.Log;
import com.shenbo.menu.BuildConfig;
/**
*
* @author: gping. gping.vip@gmail.com
* @class: L.class
* @Description:Log输入类,输入具体某个类某一行的输入
* @TODO:
*/
public class L {
/**true 打开Log输出 false关闭Log输出*/
private static boolean isLogOut = true;
public static void v(Throwable t) {
log(Log.VERBOSE, t, null);
}
public static void v(Object s1, Object... args) {
log(Log.VERBOSE, null, s1, args);
}
public static void v(Throwable t, Object s1, Object... args) {
log(Log.VERBOSE, t, s1, args);
}
public static void d(Throwable t) {
log(Log.DEBUG, t, null);
}
public static void d(Object s1, Object... args) {
log(Log.DEBUG, null, s1, args);
}
public static void d(Throwable t, Object s1, Object... args) {
log(Log.DEBUG, t, s1, args);
}
public static void i(Throwable t) {
log(Log.INFO, t, null);
}
public static void i(Object s1, Object... args) {
log(Log.INFO, null, s1, args);
}
public static void i(Throwable t, Object s1, Object... args) {
log(Log.INFO, t, s1, args);
}
public static void w(Throwable t) {
log(Log.WARN, t, null);
}
public static void w(Object s1, Object... args) {
log(Log.WARN, null, s1, args);
}
public static void w(Throwable t, Object s1, Object... args) {
log(Log.WARN, t, s1, args);
}
public static void e(Throwable t) {
log(Log.ERROR, t, null);
}
public static void e(Object s1, Object... args) {
log(Log.ERROR, null, s1, args);
}
public static void e(Throwable t, Object s1, Object... args) {
log(Log.ERROR, t, s1, args);
}
private static void log(final int pType, final Throwable t,
final Object s1, final Object... args) {
if (!isLogOut) return;
if (pType == Log.ERROR || BuildConfig.DEBUG) {
final StackTraceElement stackTraceElement = Thread.currentThread()
.getStackTrace()[4];
final String fullClassName = stackTraceElement.getClassName();
final String className = fullClassName.substring(fullClassName
.lastIndexOf(".") + 1);
final int lineNumber = stackTraceElement.getLineNumber();
final String method = stackTraceElement.getMethodName();
final String tag = className + ":" + lineNumber;
final StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(method);
stringBuilder.append("(): ");
if (s1 != null) {
final String message = (args == null) ? s1.toString() : String
.format((String) s1, args);
stringBuilder.append(message);
}
switch (pType) {
case Log.VERBOSE:
if (t != null) {
Log.v(tag, stringBuilder.toString(), t);
} else {
Log.v(tag, stringBuilder.toString());
}
break;
case Log.DEBUG:
if (t != null) {
Log.d(tag, stringBuilder.toString(), t);
} else {
Log.d(tag, stringBuilder.toString());
}
break;
case Log.INFO:
if (t != null) {
Log.i(tag, stringBuilder.toString(), t);
} else {
Log.i(tag, stringBuilder.toString());
}
break;
case Log.WARN:
if (t != null) {
Log.w(tag, stringBuilder.toString(), t);
} else {
Log.w(tag, stringBuilder.toString());
}
break;
case Log.ERROR:
if (t != null) {
Log.e(tag, stringBuilder.toString(), t);
} else {
Log.e(tag, stringBuilder.toString());
}
break;
}
}
}
public static void i() {
i("....");
}
public static void d() {
d("....");
}
public static void e() {
e("....");
}
public static void v() {
v("....");
}
public static void w() {
w("....");
}
}
| guiping/OutPutLog | L.java |
787 | package br.com.projeto.action;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class Y extends ActionSupport{
private boolean checkb;
public boolean isCheckb() {
return checkb;
}
public void setCheckb(boolean checkb) {
this.checkb = checkb;
}
public String display() {
return NONE;
}
public String execute() throws Exception{
return "success";
}
}
| rafaelfranco1/APACHESTRUTSIN2020JAVA | Y.java |
789 | class Solution {
public boolean isValidSudoku(char[][] board) {
Set<String> seen = new HashSet<>();
for (int i = 0; i < 9; ++i)
for (int j = 0; j < 9; ++j) {
if (board[i][j] == '.')
continue;
final char c = board[i][j];
if (!seen.add(c + "@row" + i) ||
!seen.add(c + "@col" + j) ||
!seen.add(c + "@box" + i / 3 + j / 3))
return false;
}
return true;
}
}
| marpitkumar/LeetCode-1 | solutions/0036. Valid Sudoku/0036.java |
790 | this is fourth
| abhi21/test_repo_game | sample4.java |
792 | today is sunday
| curram/today24 | kir |
793 | package Edureka;
import java.util.Scanner;
public class Factorial {
public static void main(String args[]){
//Scanner object for capturing the user input
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
//Stored the entered value in variable
int num = scanner.nextInt();
//Called the user defined function fact
int factorial = fact(num);
System.out.println("Factorial of entered number is: "+factorial);
}
static int fact(int n)
{
int output;
if(n==1){
return 1;
}
//Recursion: Function calling itself!!
output = fact(n-1)* n;
return output;
}
}
| Manish9823/Hacktoberfest-2021 | Factorial.java |
796 | /*
3.Read an array of 10 or more numbers and write a program to find the
1.Smallest element in the array
2.Largest element in the array
3.Second largest element in the array*/
import java.util.Scanner;
public class ArrayAnalysis {
public static void main(String[] args) {
int i,j,temp;
int arr[] = new int[10];
Scanner sc = new Scanner(System.in);
System.out.println("Enter 10 numbers :");
for(i=0;i<10;i++){
arr[i] = sc.nextInt();
}
System.out.println("Entered array :");
for(i=0;i<10;i++){
System.out.print(arr[i]+" ");
}
for(i=0;i<10;i++){
for(j=i;j<10;j++){
if(arr[i] > arr[j]){
temp = arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
System.out.println("\nSmallest element :"+arr[0]);
System.out.println("Largest element : "+arr[9]);
System.out.println("Second Largest element : "+arr[8]);
}
}
| KadeejaSahlaPV/java | 3.java |
798 | class Solution {
public static boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
int xNumDigits = 0;
int copyX2 = x;
while (true) {
if (copyX2 == 0) {
break;
}
copyX2 /= 10;
xNumDigits++;
}
int copyX = x;
int copyXNumDigits = xNumDigits;
long someX = 0;
int xReverse = 0;
for (int i = 0; i < xNumDigits; i++) {
someX += (copyX % 10) * Math.pow(10, copyXNumDigits - 1);
xReverse += (copyX % 10) * Math.pow(10, copyXNumDigits - 1);
copyXNumDigits--;
copyX /= 10;
}
System.out.println(xReverse);
return x == xReverse && someX == xReverse;
}
} | bbohosyan/LeetCode | 9.java |
800 | class p
{
int a,b;
void lol()
{
System.out.println("a="+a);
System.out.println("b="+b);
if (a<b)
{
System.out.println("b is big");
}
else
{
System.out.println("a is big");
}
}
}
class f
{
public static void main(String args[])
{
p bro=new p();
bro.a=Integer.parseInt(args[0]);
bro.b=Integer.parseInt(args[1]);
bro.lol();
}
}
| MRTHAKER/java | f.java |
812 | /*
C.java
*/
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class C extends Canvas {
private static final long serialVersionUID = 1480902466428347458L;
private static final int WIDTH = 400;
private static final int HEIGHT = 400;
private static final int RANGE = 30;
private static final int INTERVAL = 5;
private double[][] values = new double[WIDTH][HEIGHT];
private double inertia = 0.8;
private double decay = 0.9995;
private double dissipation = 0.92;
@Override
public void paint(Graphics g) {
super.paint(g);
// Initialize all pixels as blank
for (int x = 0; x < WIDTH; x++) {
for (int y = 0; y < HEIGHT; y++) {
values[x][y] = 0.0;
g.setColor(color(values[x][y]));
g.drawLine(x, y, x, y);
}
}
// Store co-ordinates of last rain-drop and time since falling
int lastX = -1;
int lastY = -1;
int lastT = -1;
while (true) {
// ~20ms per step (i.e. 50/sec)
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
// With some probability, add a rain-drop on a random location and initialize the timer
if (Math.random() < 1.0/INTERVAL) {
lastX = (int) (Math.random() * WIDTH);
lastY = (int) (Math.random() * HEIGHT);
lastT = 0;
}
// Currently, simulate water inflow at last location for three time-steps
// After, simply move drop off-canvas for simplicity
else if (lastT >= 3) {
lastX = -100;
}
lastT++;
// Compute updated values at each point in time
double[][] newValues = computeNewValues(lastX, lastY);
// Draw new canvas
for (int x = 0; x < WIDTH; x++) {
for (int y = 0; y < HEIGHT; y++) {
g.setColor(color(values[x][y]));
g.drawLine(x, y, x, y);
}
}
values = newValues;
}
}
/*
* Computes updated values given current state of canvas and last rain-drop
*/
private double[][] computeNewValues(int lastX, int lastY) {
double[][] newValues = new double[WIDTH][HEIGHT];
// For each pixel (somewhat inefficient, but fine for small canvas)
for (int i = 0; i < WIDTH; i++) {
for (int j = 0; j < HEIGHT; j++) {
double value = 0.0;
int count = 0;
// Compute distance to previous drop and if exist, simulate water inflow there
double dist = Math.sqrt(Math.pow(Math.abs(i - lastX), 2) + Math.pow(Math.abs(j - lastY), 2));
if (dist < RANGE) {
// Adjust new value by distance from drop ...
double newValue = 1.0;
while (dist-- > 0) newValue *= dissipation;
// ... but make sure not to "destroy" water that's already there
newValue = Math.max(newValue, values[i][j]);
// Update new value using inertia from old value
value = inertia * values[i][j] + (1 - inertia) * newValue;
}
// If not near new drop, simply simulate diffusion of water
else {
for (int x = i - 5; x <= i + 5; x++) {
for (int y = j - 5; y <= j + 5; y++) {
if (x < 0 || y < 0 || x >= WIDTH || y >= HEIGHT)
continue;
value += values[x][y];
count++;
}
}
value /= count;
}
// Decay values to simulate water soaking into ground
newValues[i][j] = value * decay;
}
}
return newValues;
}
private float fromValue(double value) {
return (float) (((300 * (1.0 - value) + 300) % 360) / 360.0);
}
private Color color(double value) {
return Color.getHSBColor(fromValue(value), 1.0f, .5f);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(WIDTH, HEIGHT);
frame.add(new C());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
| CMU-17-214/f22-rec12 | C.java |
814 | package com.example.jeffreynyauke.myapplication.utils;
import com.example.jeffreynyauke.myapplication.BuildConfig;
import com.orhanobut.logger.Logger;
/**
* Created by AhmedEltaher on 01/01/17.
*/
public class L {
public static void d(String tag, String massage) {
if (BuildConfig.DEBUG) {
Logger.d(tag, massage);
}
}
public static void i(String tag, String massage) {
if (BuildConfig.DEBUG) {
Logger.i(tag, massage);
}
}
public static void v(String tag, String massage) {
if (BuildConfig.DEBUG) {
Logger.v(tag, massage);
}
}
public static void e(String tag, String massage) {
if (BuildConfig.DEBUG) {
Logger.e(tag, massage);
}
}
public static void json(String tag, String massage) {
if (BuildConfig.DEBUG) {
Logger.i(tag);
Logger.json(massage);
}
}
}
| jeffnyauke/Android-Ultimate-Libraries-and-Utilities | L.java |
817 | public class Solution {
public int numOfArrays(int n, int m, int k) {
final int mod = 1000000007;
int[][] dp = new int[m+1][k+1];
int[][] prefix = new int[m+1][k+1];
int[][] prevDp = new int[m+1][k+1];
int[][] prevPrefix = new int[m+1][k+1];
for (int j = 1; j <= m; j++) {
prevDp[j][1] = 1;
prevPrefix[j][1] = j;
}
for (int i = 2; i <= n; i++) {
for (int maxNum = 1; maxNum <= m; maxNum++) {
for (int cost = 1; cost <= k; cost++) {
dp[maxNum][cost] = (int)(((long)maxNum * prevDp[maxNum][cost]) % mod);
if (maxNum > 1 && cost > 1) {
dp[maxNum][cost] = (dp[maxNum][cost] + prevPrefix[maxNum - 1][cost - 1]) % mod;
}
prefix[maxNum][cost] = (prefix[maxNum - 1][cost] + dp[maxNum][cost]) % mod;
}
}
for (int j = 1; j <= m; j++) {
System.arraycopy(dp[j], 0, prevDp[j], 0, k+1);
System.arraycopy(prefix[j], 0, prevPrefix[j], 0, k+1);
}
}
return prefix[m][k];
}
}
| Cheshta31/Daily_dsa_questions | Find_Max_Exactly_K_Comparison.java |
819 | class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
String prefix = strs[0];
for (int i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) != 0) {
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) {
return "";
}
}
}
return prefix;
}
}
| tnscjs01/LeetCode | 0014-longest-common-prefix/0014-longest-common-prefix.java |
823 | class Solution {
static int matrixMultiplication(int N, int arr[]) {
// code here
int i = 1;
int j = N - 1;
int[][] dp = new int[N + 1][N + 1];
for (int[] row : dp)
Arrays.fill(row, -1);
int ans = solve(arr, i, j, dp);
return ans;
}
static int solve(int[] arr, int n, int m, int[][] dp) {
if (n >= m)
return 0;
if (dp[n][m] != -1)
return dp[n][m];
int mn = Integer.MAX_VALUE;
for (int k = n; k < m; k++) {
int temp = solve(arr, n, k, dp) + solve(arr, k + 1, m, dp) + arr[n - 1] * arr[k] * arr[m];
if (temp < mn)
mn = temp;
}
dp[n][m] = mn;
return dp[n][m];
}
}
| ankit21311/DPP-7-Days | Q5 |
825 | public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry =0;
ListNode newHead = new ListNode(0);
ListNode p1 = l1, p2 = l2, p3=newHead;
while(p1 != null || p2 != null){
if(p1 != null){
carry += p1.val;
p1 = p1.next;
}
if(p2 != null){
carry += p2.val;
p2 = p2.next;
}
p3.next = new ListNode(carry%10);
p3 = p3.next;
carry /= 10;
}
if(carry==1)
p3.next=new ListNode(1);
return newHead.next;
}
}{
}
| Beyondtarun/leetcode | 2.java |
826 | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
class QueryRunner implements Runnable {
// Declare socket for client access
protected Socket socketConnection;
public QueryRunner(Socket clientSocket) {
this.socketConnection = clientSocket;
}
public void run() {
try {
// Reading data from client
InputStreamReader inputStream = new InputStreamReader(socketConnection
.getInputStream());
BufferedReader bufferedInput = new BufferedReader(inputStream);
OutputStreamWriter outputStream = new OutputStreamWriter(socketConnection
.getOutputStream());
BufferedWriter bufferedOutput = new BufferedWriter(outputStream);
PrintWriter printWriter = new PrintWriter(bufferedOutput, true);
String clientCommand = "";
String responseQuery = "";
// Read client query from the socket endpoint
clientCommand = bufferedInput.readLine();
int size=0;
String train_number;
String coach_type;
String date ;
String query = "";
try {
while (!clientCommand.equals("#")) {
String[] splited = clientCommand.split("\\s+");
size = splited.length;
train_number = splited[size - 3];
coach_type = splited[size - 1];
date = splited[size - 2];
query= String.format("select insert_ticket( %s , '%s' , '%s' , '%s' , array[",splited[0],train_number,coach_type,date);
for (int i=1;i<size-3;i++){
if( splited[i].endsWith(",")){
splited[i] = splited[i].substring(0, splited[i].length() - 1);
query=String.format("%s'%s',",query,splited[i]);
}
else{
query=String.format("%s'%s'",query,splited[i]);
}
}
System.out.println(query);
clientCommand = bufferedInput.readLine();
}
printWriter.println(responseQuery);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
inputStream.close();
bufferedInput.close();
outputStream.close();
bufferedOutput.close();
printWriter.close();
socketConnection.close();
} catch (IOException e) {
return;
}
}
}
/**
* Main Class to controll the program flow
*/
public class e {
// Server listens to port
static int serverPort = 7008;
// Max no of parallel requests the server can process
static int numServerCores = 50;
// ------------ Main----------------------
public static void main(String[] args) throws IOException {
// Creating a thread pool
ExecutorService executorService = Executors.newFixedThreadPool(numServerCores);
try (// Creating a server socket to listen for clients
ServerSocket serverSocket = new ServerSocket(serverPort)) {
Socket socketConnection = null;
// Always-ON server
while (true) {
System.out.println("Listening port : " + serverPort
+ "\nWaiting for clients...");
socketConnection = serverSocket.accept(); // Accept a connection from a client
System.out.println("Accepted client :"
+ socketConnection.getRemoteSocketAddress().toString()
+ "\n");
// Create a runnable task
Runnable runnableTask = new QueryRunner(socketConnection);
// Submit task for execution
executorService.submit(runnableTask);
}
}
}
}
| SOURABH-SANGANWAR/CS301_Project | e.java |
827 | // Merge Strings Alternately
class Solution {
public String mergeAlternately(String word1, String word2) {
StringBuilder ans = new StringBuilder();
int p1 = 0, p2 = 0;
while (p1 < word1.length() && p2 < word2.length()) {
ans.append(word1.charAt(p1++));
ans.append(word2.charAt(p2++));
}
// Append remaining characters of word1, if any
while (p1 < word1.length()) {
ans.append(word1.charAt(p1++));
}
// Append remaining characters of word2, if any
while (p2 < word2.length()) {
ans.append(word2.charAt(p2++));
}
return ans.toString();
}
}
| Aryan201903/Leetcode75 | 1.java |
829 | public class solution
{
public static int securiyKey(int data)
{
int result = 0;
int[] arr = new int[10];
int i = 0;
while(data > 0)
{
arr[i] = data % 10;
data = data / 10;
i++;
}
for(int j = 0; j < i; j++)
{
result = result * 10 + arr[j];
}
return result;
}
public static void main(String[] args)
{
int data = 123456789;
System.out.println(securiyKey(data));
}
}
// Path: 2.java
public class solution
{
public static int securiyKey(int data)
{
int result = 0;
while(data > 0)
{
result = result * 10 + data % 10;
data = data / 10;
}
return result;
}
public static void main(String[] args)
{
int data = 123456789;
System.out.println(securiyKey(data));
}
}
// Path: 3.java
| Pravin190/final-project | 1.java |
833 | class Solution {
static int lengthOfLongestSubstring(String s) {
int result = 0, left = 0;
int[] index = new int[128];
for (int i = 0; i < s.length(); i++) {
left = Math.max(left, index[s.charAt(i)]);
index[s.charAt(i)] = i + 1;
result = Math.max(result, i - left + 1);
}
return result;
}
}
| MaarcusRenieroL/leetcode-solutions | 3.java |
836 | class Solution {
public int maxSubArray(int[] nums) {
int maxSum = nums[0];
int currentSum = nums[0];
for (int i = 1; i < nums.length; i++) {
currentSum = Math.max(nums[i], currentSum + nums[i]);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}
}
| JoshGaviola/leetcode | 53.) Maximum Subarray/solution.java |
837 | class Solution {
public String longestPalindrome(String s) {
int len = 0;
int left = 0;
int right = 0;
for(int i=0;i<s.length();i++){
int start = i;
int end = i;
while(start>=0 && end<s.length() && s.charAt(start) == s.charAt(end)){
if(len < end-start+1){
len = end-start+1;
left = start;
right = end;
}
start--;
end++;
}
start = i;
end = i+1;
while(start>=0 && end<s.length() && s.charAt(start) == s.charAt(end)){
if(len < end-start+1){
len = end-start+1;
left = start;
right = end;
}
start--;
end++;
}
}
return s.substring(left, right+1);
}
} | iamtanbirahmed/100DaysOfLC | 5.java |
838 | class Solution {
public String longestPalindrome(String s) {
// Loop through centers
int longestBegin = 0;
int longestEnd = 0;
for (int i = 0; i < s.length(); i++) {
// Loop while char before and char after
// are equal
int begin = i;
int end = i;
while (begin >= 0 && end < s.length()
&& s.charAt(begin) == s.charAt(end)) {
begin--;
end++;
}
// Revert back once since the condition is no
// longer back
begin++;
end--;
if (end - begin > longestEnd - longestBegin) {
longestBegin = begin;
longestEnd = end;
}
// Loop while char before and char after
// are equal
begin = i;
end = i + 1;
while (begin >= 0 && end < s.length()
&& s.charAt(begin) == s.charAt(end)) {
begin--;
end++;
}
// Revert back once since the condition is no
// longer back
begin++;
end--;
if (end - begin > longestEnd - longestBegin) {
longestBegin = begin;
longestEnd = end;
}
}
return s.substring(longestBegin, longestEnd + 1);
}
}
| loukylor/LeetCodeSolutions | 5.java |
841 | /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0); // Create a dummy head node.
ListNode p = l1, q = l2, current = dummy;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
current.next = new ListNode(sum % 10);
if (p != null) p = p.next;
if (q != null) q = q.next;
current = current.next;
}
if (carry > 0) {
current.next = new ListNode(carry);
}
return dummy.next;
}
}
| thisizaro/leetcodeProblems | 2.java |
842 | // https://www.hackerrank.com/challenges/java-end-of-file/problem
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
for(int i = 1; scan.hasNext()== true; i++){
System.out.println(i + " " + scan.nextLine());
}
}
}
| haytastan/Hackerrank_Java | 9.java |
843 | package com.company.string;
public class kmp_construction_lps {
static int longPropPreSuff(String str, int n){
System.out.println(n-1);
for(int len=n-1;len>0;len--){
System.out.println(len);
boolean flag=true;
for(int i=0;i<len;i++)
if(str.charAt(i)!=str.charAt(n-len+i))
flag=false;
if(flag==true)
return len;
}
return 0;
}
static void naive_fillLPS(String str, int lps[]){
for(int i=0;i<str.length();i++){
lps[i]=longPropPreSuff(str,i+1);
}
}
static void efficient_fillLPS(String str, int lps[]){
int n=str.length(),len=0;
lps[0]=0;
int i=1;
while(i<n){
if(str.charAt(i)==str.charAt(len))
{len++;lps[i]=len;i++;}
else
{if(len==0){lps[i]=0;i++;}
else{len=lps[len-1];}
}
}
}
public static void main(String args[])
{ String txt = "aaacabad";int[] lps=new int[txt.length()];
efficient_fillLPS(txt,lps);
for(int i=0;i<txt.length();i++){
System.out.print(lps[i]+" ");
}
}
}
| Gauravarora017/Data-Structures | kmp_construction_lps.java |
844 | class Solution {
public boolean isPalindrome(int x) {
if (x<0){
return false;
}
if (x==0){
return true;
}
int res = 0;
int original = x;
while (x!=0){
res=x%10+10*res;
x/=10;
}
return original==res;
}
} | mikelyy/Leetcode | 9.java |
845 | // Increasing triplet subsequence
class Solution {
public boolean increasingTriplet(int[] nums) {
if (nums == null || nums.length < 3) {
return false;
}
int a = Integer.MAX_VALUE;
int b = Integer.MAX_VALUE;
for (int num : nums) {
if(num <= a) a = num;
else if(num <= b) b = num;
else return true;
}
return false;
}
}
| Aryan201903/Leetcode75 | 8.java |
847 | class Solution {
public int mostFrequentEven(int[] nums) {
int temp[] = new int[100001];
for(int i : nums) temp[i]++;
int min = 100000 , freq = 0 , ans = -1;
for(int i=0; i<temp.length; i++){
if(i%2==0 && freq<temp[i]){
freq = temp[i];
ans = i;
}
}
return ans;
}
}
| astro1sumit/leetcodechallenge | 2404 |
848 | import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ItemEvent;
public class ColorDemo extends JFrame implements
ItemListener
{
int r=0,g=0,b=0;
JCheckBox red,green,blue,yellow,white;
JPanel P=new JPanel();
JPanel cpanel=new JPanel();
Container pane=getContentPane();
ButtonGroup group=new ButtonGroup();
ColorDemo(String cd)
{
super(cd);
red=new JCheckBox("red");
red.addItemListener(this);
green=new JCheckBox("green");
green.addItemListener(this);
blue=new JCheckBox("blue");
blue.addItemListener(this);
yellow=new JCheckBox("yellow");
yellow.addItemListener(this);
white=new JCheckBox("white");
white.addItemListener(this);
group.add(red);
group.add(green);
group.add(blue);
group.add(yellow);
group.add(white);
cpanel.add(red);
cpanel.add(green);
cpanel.add(blue);
cpanel.add(yellow);
cpanel.add(white);
getContentPane().add(cpanel,"North");
setSize(400,400);
setVisible(true);
getContentPane().add(P);
setVisible(true);
}
public static void main(String[] args)
{
ColorDemo cd=new ColorDemo("ColorCheckBox");
cd.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void itemStateChanged(ItemEvent ie) {
if(ie.getItem()==red)
P.setBackground(new Color(255,0,0));
else if(ie.getItem()==green)
P.setBackground(new Color(0,255,0));
else if(ie.getItem()==blue)
P.setBackground(new Color(0,0,255));
else if(ie.getItem()==yellow)
P.setBackground(new Color(255,255,0));
else if(ie.getItem()==white)
P.setBackground(new Color(255,255,255));
}
}
| Jeevananthamcse/Java-Programs | o.java |
849 | // Recursive Java program for insertion sort
import java.util.Arrays;
public class GFG
{
// Recursive function to sort an array using
// insertion sort
static void insertionSortRecursive(int arr[], int n)
{
// Base case
if (n <= 1)
return;
// Sort first n-1 elements
insertionSortRecursive( arr, n-1 );
// Insert last element at its correct position
// in sorted array.
int last = arr[n-1];
int j = n-2;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > last)
{
arr[j+1] = arr[j];
j--;
}
arr[j+1] = last;
}
// Driver Method
public static void main(String[] args)
{
int arr[] = {12, 11, 13, 5, 6};
insertionSortRecursive(arr, arr.length);
System.out.println(Arrays.toString(arr));
}
}
| avi-pal/Let-Us-Java | Sorting/Recursive_insertion_sort.java |
851 | package com.hailei.service;
import com.hailei.pojo.Brand;
import com.hailei.pojo.PageBean;
import java.util.List;
public interface BrandService {
/**
* 查询所有
* @return
*/
List<Brand> selectAll();
/**
* 添加数据
* @param brand
*/
void add(Brand brand);
/**
* 删除
* @param id
*/
void deleteById(int id);
/**
* 修改
* @param brand
*/
void updateById(Brand brand);
/**
* 批量删除
* @param ids
*/
void deleteByIds( int[] ids);
/**
* 分页查询
* @param currentPage 当前页码
* @param pageSize 每页展示条数
* @return
*/
PageBean<Brand> selectByPage(int currentPage,int pageSize);
/**
* 分页条件查询
* @param currentPage
* @param pageSize
* @param brand
* @return
*/
PageBean<Brand> selectByPageAndCondition(int currentPage,int pageSize,Brand brand);
}
| rewdf3/rewdf3 | rdtd |
852 | package b.java;
public class B {
public void method2 {
System.out.println("This is a modified line in method2 (done on my-branch");
System.out.println("Added line in my-branch");
}
public void method2b {
System.out.println("Added Method 2b");
}
public void methodNew {
System.out.println("Adding this method to test pull request.");
}
}
| jaythecelt/test-repo | b.java |
853 | class Problem3 {
public int lengthOfLongestSubstring(String s) {
//O(n^2) runtime solution
/*int m = 0;
for (int i = 0; i < s.length(); i++){
String currString = Character.toString(s.charAt(i));
m = Math.max(m, currString.length());
for (int j = i+1; j < s.length(); j++){
if (currString.indexOf(s.charAt(j)) == -1){
currString += s.charAt(j);
m = Math.max(m, currString.length());
}
else j = s.length();
}
m = Math.max(m, currString.length());
}
return m;
*/
//O(n) runtime solution
int m = 0;
String curr = "";
if (s.length() == 0) return m;
curr += s.charAt(0);
m = Math.max(m, curr.length());
for (int i = 1; i < s.length(); i++){
if (curr.indexOf(s.charAt(i)) != -1)
curr = curr.substring(curr.indexOf(s.charAt(i)) + 1) + Character.toString(s.charAt(i));
else
curr += s.charAt(i);
m = Math.max(m, curr.length());
}
return m;
}
} | rkibel/LeetCode | 3.java |
854 | // https://leetcode.com/contest/weekly-contest-386/problems/find-the-largest-area-of-square-inside-two-rectangles/
class Main {
public static void main(String[] args) {
// Note: Don't change class name
// your code goes here
}
}
class Solution {
int common(int l1, int r1, int l2, int r2) {
int ans = Math.min(r1, r2) - Math.max(l1, l2);
return Math.max(ans, 0);
}
public long largestSquareArea(int[][] bottomLeft, int[][] topRight) {
long ans = 0;
for(int i = 0; i < bottomLeft.length; ++i)
for(int j = i + 1; j < bottomLeft.length; ++j) {
// (xibl,yibl) | (xitr, yitr);
// (xjbl,yjbl) | (xjtr, yjtr);
long len = Math.min(common(bottomLeft[i][0], topRight[i][0], bottomLeft[j][0], topRight[j][0]), common(bottomLeft[i][1], topRight[i][1], bottomLeft[j][1], topRight[j][1]));
ans = Math.max(ans, len*len);
}
return ans;
}
} | Premkumar981/Java | 2.java |
855 | package com.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("/json/service")
public class JSONService {
@GET
@Path("/get")
@Produces("application/json")
public Product getApplication() {
Product p=new Product();
p.setName("shi");
p.setId(180);
return p;
}
//
// @POST
//
// @Path("/post")
//
// @Consumes("application/json")
//
//
//
// public void postApplication(Product p)
//
//
//
// {
//
//
//
// System.out.println(p.getName()+" "+p.getId());
//
//
//
// }
//
}
package com.rest;
public class Product {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
String name;
int id;
}
| Ranganathb082/hackerrank-problems | 9.java |
856 | package com.ubicua.smartstreet;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
class ServerConnectionThread extends Thread{
private SelectCalleActivity activity;
private String tag = "ServerConnectionThread";
private String urlStr = "";
public ServerConnectionThread(SelectCalleActivity activ, String url) {
activity = activ;
urlStr = url;
start();
}
@Override
public void run() {
String response = "";
try {
System.out.println("Corriendo");
URL url = new URL(urlStr);
HttpURLConnection urlConnection = null;
urlConnection = (HttpURLConnection) url.openConnection();
//Get the information from the url
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
response = convertStreamToString(in);
Log.d(tag, "get json: " + response);
JSONArray jsonarray = new JSONArray(response);
//Read Responses and fill the spinner
System.out.println("Corriendo2");
if(urlStr.contains("GetZonasCiudad"))
{
activity.setListZonas(jsonarray);
}
else if(urlStr.contains("GetCallesZona"))
{
activity.setListCalles(jsonarray);
}
else if(urlStr.contains("GetSensoresCalle"))
{
activity.setJsonValores(jsonarray);
}
else if(urlStr.contains("GetHorasPuntaCalle"))
{
activity.setHoras(jsonarray);
}else if(urlStr.contains("GetCiudades"))
{
Log.e(tag,"HEllo there");
activity.setCiudades(jsonarray);
}
}
catch (IOException | JSONException e) {
e.printStackTrace();
}
}
//Get the input strean and convert into String
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
| RaulMoratilla/ComputacionUbicuaG06 | Thread |
858 | class Solution {
public int lengthOfLongestSubstring(String s) {
int start = 0;
int end = 0;
Map<Character, Integer> count = new HashMap();
int len = 0;
while(end<s.length()){
char ch = s.charAt(end);
count.put(ch, count.getOrDefault(ch, 0)+1);
while(count.get(ch)>1){
char ch2 = s.charAt(start);
count.put(ch2, count.get(ch2)-1);
start++;
}
len = Math.max(len, end-start+1);
end++;
}
return len;
}
} | iamtanbirahmed/100DaysOfLC | 3.java |
859 | class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& A) {
int n = A.size();
int m = A[0].size();
vector<vector<int>> ans(n, vector<int>(m, 0));
for (int i = 0; i < n; i++) {
if (A[i][0] == 0)
ans[i][0] = 1;
else
break;
}
for (int j = 0; j < m; j++) {
if (A[0][j] == 0)
ans[0][j] = 1;
else
break;
}
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
if (A[i][j] == 0)
ans[i][j] = ans[i-1][j] + ans[i][j-1];
}
}
return ans[n-1][m-1];
}
}; | yugbit2021/Leetcode | 63.cpp |
860 | class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> allCharacters = new HashSet<>();
char[] sArray = s.toCharArray();
int maxLength = 0;
int currentLength = 0;
for (int startingPosition = 0; startingPosition < s.length(); startingPosition++){
for (int j = startingPosition; j < s.length(); j++){
if (allCharacters.contains(sArray[j])){
break;
}
else {
allCharacters.add(sArray[j]);
currentLength++;
}
}
if (currentLength > maxLength){
maxLength = currentLength;
}
currentLength = 0;
allCharacters = new HashSet<>();
}
return maxLength;
}
} | bbohosyan/LeetCode | 3.java |
861 | import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class InvalidCharacterException extends Exception {
public InvalidCharacterException(String message) {
super(message);
}
}
public class FileParsingExample {
public static void main(String[] args) {
String sourceFileName = "alphabets.txt";
String consonantsFileName = "consonants.txt";
String vowelsFileName = "vowels.txt";
try {
File sourceFile = new File(sourceFileName);
FileReader fileReader = new FileReader(sourceFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
File consonantsFile = new File(consonantsFileName);
FileWriter consonantsFileWriter = new FileWriter(consonantsFile);
File vowelsFile = new File(vowelsFileName);
FileWriter vowelsFileWriter = new FileWriter(vowelsFile);
int charInt;
while ((charInt = bufferedReader.read()) != -1) {
char character = (char) charInt;
if (Character.isLetter(character)) {
if (isVowel(character)) {
vowelsFileWriter.write(character);
} else {
consonantsFileWriter.write(character);
}
} else if (Character.isDigit(character)) {
throw new InvalidCharacterException("Invalid character (digit) found in the file: " + character);
}
}
bufferedReader.close();
consonantsFileWriter.close();
vowelsFileWriter.close();
System.out.println("Files created successfully.");
} catch (IOException e) {
System.err.println("Error occurred while reading/writing files: " + e.getMessage());
} catch (InvalidCharacterException e) {
System.err.println(e.getMessage());
}
}
private static boolean isVowel(char ch) {
ch = Character.toLowerCase(ch);
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}
}
| r-vb/OOP | 05.java |
862 | public class x{
float cX;
float cY;
float cRotation;
float distanceStrafed;
float rightWheel, leftWheel, middleWheel, wheelDistance;
float theta(){
return (rightWheel/leftWheel)/wheelDistance;
}
float getX(){
return cX+((middleWheel/theta())*Math.sin((theta())))*Math.cos(cRotation+(theta()/2))+middleWheel*Math.cos(cRotation-(Math.PI/2)+theta()/2);
}
float getY(){
return cY+((middleWheel/theta())*Math.sin((theta())))/Math.cos(cRotation+(theta()/2))+middleWheel*Math.sin(cRotation-(Math.PI/2)+theta()/2);
}
float getRotation(){
return cRotation+theta();
}
void main(){
cX=getX();
cY=getY();
cRotation=getRotation();
}
} | cvaz1306/MoscowMechanicsCode | x.java |
863 | import com.google.common.base.Functions;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.primitives.Doubles;
import com.google.gson.JsonParseException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import net.minecraft.server.MinecraftServer;
import org.apache.commons.lang3.exception.ExceptionUtils;
public abstract class i
implements k
{
private static h a;
protected static cc a(JsonParseException ☃)
{
Throwable ☃ = ExceptionUtils.getRootCause(☃);
String ☃ = "";
if (☃ != null)
{
☃ = ☃.getMessage();
if (☃.contains("setLenient")) {
☃ = ☃.substring(☃.indexOf("to accept ") + 10);
}
}
return new cc("commands.tellraw.jsonException", new Object[] { ☃ });
}
protected static dn a(rr ☃)
{
dn ☃ = new dn();
☃.e(☃);
if ((☃ instanceof zj))
{
adq ☃ = ((zj)☃).br.h();
if ((☃ != null) && (☃.b() != null)) {
☃.a("SelectedItem", ☃.b(new dn()));
}
}
return ☃;
}
public int a()
{
return 4;
}
public List<String> b()
{
return Collections.emptyList();
}
public boolean a(MinecraftServer ☃, m ☃)
{
return ☃.a(a(), c());
}
public List<String> a(MinecraftServer ☃, m ☃, String[] ☃, cj ☃)
{
return Collections.emptyList();
}
public static int a(String ☃)
throws cb
{
try
{
return Integer.parseInt(☃);
}
catch (NumberFormatException ☃)
{
throw new cb("commands.generic.num.invalid", new Object[] { ☃ });
}
}
public static int a(String ☃, int ☃)
throws cb
{
return a(☃, ☃, Integer.MAX_VALUE);
}
public static int a(String ☃, int ☃, int ☃)
throws cb
{
int ☃ = a(☃);
if (☃ < ☃) {
throw new cb("commands.generic.num.tooSmall", new Object[] { Integer.valueOf(☃), Integer.valueOf(☃) });
}
if (☃ > ☃) {
throw new cb("commands.generic.num.tooBig", new Object[] { Integer.valueOf(☃), Integer.valueOf(☃) });
}
return ☃;
}
public static long b(String ☃)
throws cb
{
try
{
return Long.parseLong(☃);
}
catch (NumberFormatException ☃)
{
throw new cb("commands.generic.num.invalid", new Object[] { ☃ });
}
}
public static long a(String ☃, long ☃, long ☃)
throws cb
{
long ☃ = b(☃);
if (☃ < ☃) {
throw new cb("commands.generic.num.tooSmall", new Object[] { Long.valueOf(☃), Long.valueOf(☃) });
}
if (☃ > ☃) {
throw new cb("commands.generic.num.tooBig", new Object[] { Long.valueOf(☃), Long.valueOf(☃) });
}
return ☃;
}
public static cj a(m ☃, String[] ☃, int ☃, boolean ☃)
throws cb
{
cj ☃ = ☃.c();
return new cj(b(☃.p(), ☃[☃], -30000000, 30000000, ☃), b(☃.q(), ☃[(☃ + 1)], 0, 256, false), b(☃.r(), ☃[(☃ + 2)], -30000000, 30000000, ☃));
}
public static double c(String ☃)
throws cb
{
try
{
double ☃ = Double.parseDouble(☃);
if (!Doubles.isFinite(☃)) {
throw new cb("commands.generic.num.invalid", new Object[] { ☃ });
}
return ☃;
}
catch (NumberFormatException ☃)
{
throw new cb("commands.generic.num.invalid", new Object[] { ☃ });
}
}
public static double a(String ☃, double ☃)
throws cb
{
return a(☃, ☃, Double.MAX_VALUE);
}
public static double a(String ☃, double ☃, double ☃)
throws cb
{
double ☃ = c(☃);
if (☃ < ☃) {
throw new cb("commands.generic.double.tooSmall", new Object[] { Double.valueOf(☃), Double.valueOf(☃) });
}
if (☃ > ☃) {
throw new cb("commands.generic.double.tooBig", new Object[] { Double.valueOf(☃), Double.valueOf(☃) });
}
return ☃;
}
public static boolean d(String ☃)
throws bz
{
if ((☃.equals("true")) || (☃.equals("1"))) {
return true;
}
if ((☃.equals("false")) || (☃.equals("0"))) {
return false;
}
throw new bz("commands.generic.boolean.invalid", new Object[] { ☃ });
}
public static lr a(m ☃)
throws cd
{
if ((☃ instanceof lr)) {
return (lr)☃;
}
throw new cd("You must specify which player you wish to perform this action on.", new Object[0]);
}
public static lr a(MinecraftServer ☃, m ☃, String ☃)
throws cd
{
lr ☃ = o.a(☃, ☃);
if (☃ == null) {
try
{
☃ = ☃.al().a(UUID.fromString(☃));
}
catch (IllegalArgumentException localIllegalArgumentException) {}
}
if (☃ == null) {
☃ = ☃.al().a(☃);
}
if (☃ == null) {
throw new cd();
}
return ☃;
}
public static rr b(MinecraftServer ☃, m ☃, String ☃)
throws ca
{
return a(☃, ☃, ☃, rr.class);
}
public static <T extends rr> T a(MinecraftServer ☃, m ☃, String ☃, Class<? extends T> ☃)
throws ca
{
rr ☃ = o.a(☃, ☃, ☃);
if (☃ == null) {
☃ = ☃.al().a(☃);
}
if (☃ == null) {
try
{
UUID ☃ = UUID.fromString(☃);
☃ = ☃.a(☃);
if (☃ == null) {
☃ = ☃.al().a(☃);
}
}
catch (IllegalArgumentException ☃)
{
throw new ca("commands.generic.entity.invalidUuid", new Object[0]);
}
}
if ((☃ == null) || (!☃.isAssignableFrom(☃.getClass()))) {
throw new ca();
}
return ☃;
}
public static List<rr> c(MinecraftServer ☃, m ☃, String ☃)
throws ca
{
if (o.b(☃)) {
return o.b(☃, ☃, rr.class);
}
return Lists.newArrayList(new rr[] { b(☃, ☃, ☃) });
}
public static String d(MinecraftServer ☃, m ☃, String ☃)
throws cd
{
try
{
return a(☃, ☃, ☃).h_();
}
catch (cd ☃)
{
if ((☃ == null) || (☃.startsWith("@"))) {
throw ☃;
}
}
return ☃;
}
public static String e(MinecraftServer ☃, m ☃, String ☃)
throws ca
{
try
{
return a(☃, ☃, ☃).h_();
}
catch (cd ☃)
{
try
{
return b(☃, ☃, ☃).bc().toString();
}
catch (ca ☃)
{
if ((☃ == null) || (☃.startsWith("@"))) {
throw ☃;
}
}
}
return ☃;
}
public static eu a(m ☃, String[] ☃, int ☃)
throws cd
{
return b(☃, ☃, ☃, false);
}
public static eu b(m ☃, String[] ☃, int ☃, boolean ☃)
throws cd
{
eu ☃ = new fa("");
for (int ☃ = ☃; ☃ < ☃.length; ☃++)
{
if (☃ > ☃) {
☃.a(" ");
}
eu ☃ = new fa(☃[☃]);
if (☃)
{
eu ☃ = o.b(☃, ☃[☃]);
if (☃ == null)
{
if (o.b(☃[☃])) {
throw new cd();
}
}
else {
☃ = ☃;
}
}
☃.a(☃);
}
return ☃;
}
public static String a(String[] ☃, int ☃)
{
StringBuilder ☃ = new StringBuilder();
for (int ☃ = ☃; ☃ < ☃.length; ☃++)
{
if (☃ > ☃) {
☃.append(" ");
}
String ☃ = ☃[☃];
☃.append(☃);
}
return ☃.toString();
}
public static i.a a(double ☃, String ☃, boolean ☃)
throws cb
{
return a(☃, ☃, -30000000, 30000000, ☃);
}
public static i.a a(double ☃, String ☃, int ☃, int ☃, boolean ☃)
throws cb
{
boolean ☃ = ☃.startsWith("~");
if ((☃) && (Double.isNaN(☃))) {
throw new cb("commands.generic.num.invalid", new Object[] { Double.valueOf(☃) });
}
double ☃ = 0.0D;
if ((!☃) || (☃.length() > 1))
{
boolean ☃ = ☃.contains(".");
if (☃) {
☃ = ☃.substring(1);
}
☃ += c(☃);
if ((!☃) && (!☃) && (☃)) {
☃ += 0.5D;
}
}
if ((☃ != 0) || (☃ != 0))
{
if (☃ < ☃) {
throw new cb("commands.generic.double.tooSmall", new Object[] { Double.valueOf(☃), Integer.valueOf(☃) });
}
if (☃ > ☃) {
throw new cb("commands.generic.double.tooBig", new Object[] { Double.valueOf(☃), Integer.valueOf(☃) });
}
}
return new i.a(☃ + (☃ ? ☃ : 0.0D), ☃, ☃);
}
public static double b(double ☃, String ☃, boolean ☃)
throws cb
{
return b(☃, ☃, -30000000, 30000000, ☃);
}
public static double b(double ☃, String ☃, int ☃, int ☃, boolean ☃)
throws cb
{
boolean ☃ = ☃.startsWith("~");
if ((☃) && (Double.isNaN(☃))) {
throw new cb("commands.generic.num.invalid", new Object[] { Double.valueOf(☃) });
}
double ☃ = ☃ ? ☃ : 0.0D;
if ((!☃) || (☃.length() > 1))
{
boolean ☃ = ☃.contains(".");
if (☃) {
☃ = ☃.substring(1);
}
☃ += c(☃);
if ((!☃) && (!☃) && (☃)) {
☃ += 0.5D;
}
}
if ((☃ != 0) || (☃ != 0))
{
if (☃ < ☃) {
throw new cb("commands.generic.double.tooSmall", new Object[] { Double.valueOf(☃), Integer.valueOf(☃) });
}
if (☃ > ☃) {
throw new cb("commands.generic.double.tooBig", new Object[] { Double.valueOf(☃), Integer.valueOf(☃) });
}
}
return ☃;
}
public static class a
{
private final double a;
private final double b;
private final boolean c;
protected a(double ☃, double ☃, boolean ☃)
{
this.a = ☃;
this.b = ☃;
this.c = ☃;
}
public double a()
{
return this.a;
}
public double b()
{
return this.b;
}
public boolean c()
{
return this.c;
}
}
public static ado a(m ☃, String ☃)
throws cb
{
kk ☃ = new kk(☃);
ado ☃ = (ado)ado.f.c(☃);
if (☃ == null) {
throw new cb("commands.give.item.notFound", new Object[] { ☃ });
}
return ☃;
}
public static ajt b(m ☃, String ☃)
throws cb
{
kk ☃ = new kk(☃);
if (!ajt.h.d(☃)) {
throw new cb("commands.give.block.notFound", new Object[] { ☃ });
}
ajt ☃ = (ajt)ajt.h.c(☃);
if (☃ == null) {
throw new cb("commands.give.block.notFound", new Object[] { ☃ });
}
return ☃;
}
public static String a(Object[] ☃)
{
StringBuilder ☃ = new StringBuilder();
for (int ☃ = 0; ☃ < ☃.length; ☃++)
{
String ☃ = ☃[☃].toString();
if (☃ > 0) {
if (☃ == ☃.length - 1) {
☃.append(" and ");
} else {
☃.append(", ");
}
}
☃.append(☃);
}
return ☃.toString();
}
public static eu a(List<eu> ☃)
{
eu ☃ = new fa("");
for (int ☃ = 0; ☃ < ☃.size(); ☃++)
{
if (☃ > 0) {
if (☃ == ☃.size() - 1) {
☃.a(" and ");
} else if (☃ > 0) {
☃.a(", ");
}
}
☃.a((eu)☃.get(☃));
}
return ☃;
}
public static String a(Collection<String> ☃)
{
return a(☃.toArray(new String[☃.size()]));
}
public static List<String> a(String[] ☃, int ☃, cj ☃)
{
if (☃ == null) {
return Lists.newArrayList(new String[] { "~" });
}
int ☃ = ☃.length - 1;
String ☃;
if (☃ == ☃)
{
☃ = Integer.toString(☃.p());
}
else
{
String ☃;
if (☃ == ☃ + 1)
{
☃ = Integer.toString(☃.q());
}
else
{
String ☃;
if (☃ == ☃ + 2) {
☃ = Integer.toString(☃.r());
} else {
return Collections.emptyList();
}
}
}
String ☃;
return Lists.newArrayList(new String[] { ☃ });
}
public static List<String> b(String[] ☃, int ☃, cj ☃)
{
if (☃ == null) {
return Lists.newArrayList(new String[] { "~" });
}
int ☃ = ☃.length - 1;
String ☃;
if (☃ == ☃)
{
☃ = Integer.toString(☃.p());
}
else
{
String ☃;
if (☃ == ☃ + 1) {
☃ = Integer.toString(☃.r());
} else {
return null;
}
}
String ☃;
return Lists.newArrayList(new String[] { ☃ });
}
public static boolean a(String ☃, String ☃)
{
return ☃.regionMatches(true, 0, ☃, 0, ☃.length());
}
public static List<String> a(String[] ☃, String... ☃)
{
return a(☃, Arrays.asList(☃));
}
public static List<String> a(String[] ☃, Collection<?> ☃)
{
String ☃ = ☃[(☃.length - 1)];
List<String> ☃ = Lists.newArrayList();
if (!☃.isEmpty())
{
for (String ☃ : Iterables.transform(☃, Functions.toStringFunction())) {
if (a(☃, ☃)) {
☃.add(☃);
}
}
if (☃.isEmpty()) {
for (Object ☃ : ☃) {
if (((☃ instanceof kk)) &&
(a(☃, ((kk)☃).a()))) {
☃.add(String.valueOf(☃));
}
}
}
}
return ☃;
}
public boolean b(String[] ☃, int ☃)
{
return false;
}
public static void a(m ☃, k ☃, String ☃, Object... ☃)
{
a(☃, ☃, 0, ☃, ☃);
}
public static void a(m ☃, k ☃, int ☃, String ☃, Object... ☃)
{
if (a != null) {
a.a(☃, ☃, ☃, ☃, ☃);
}
}
public static void a(h ☃)
{
a = ☃;
}
public int a(k ☃)
{
return c().compareTo(☃.c());
}
}
| MCLabyMod/LabyMod-1.9 | i.java |
864 | abstract class Shape
{
abstract void numberOfSides();
}
class Rectangle extends Shape
{
void numberOfSides()
{
System.out.println("Number of sides in a rectangle:4");
}
}
class Traingle extends Shape
{
void numberOfSides()
{
System.out.println("Number of sides in a triangle:3");
}
}
class Hexagon extends Shape
{
void numberOfSides()
{
System.out.println("Number of sides in a hexagon:6");
}
}
class main
{
public static void main(String args[])
{
Rectangle obj1=new Rectangle();
Traingle obj2=new Traingle();
Hexagon obj3=new Hexagon();
obj1.numberOfSides();
obj2.numberOfSides();
obj3.numberOfSides();
}
}
| miraz00/exp4 | 2.java |
870 | class Solution {
static int reverseInteger(int n) {
double result = 0;
boolean isNegative = n < 0;
n = n < 0 ? n * -1 : n;
while (n != 0) {
result = result * 10 + n % 10;
n /= 10;
}
if (isNegative) {
result *= -1;
}
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
return 0;
}
return (int) result;
}
}
| MaarcusRenieroL/leetcode-solutions | 7.java |
872 | //https://leetcode.com/problems/invert-binary-tree/
class Solution {
public TreeNode invertTree(TreeNode root) {
invert(root);
return root;
}
private void invert(TreeNode node){
if(node== null) return;
TreeNode tmp = node.left;
node.left = node.right;
node.right = tmp;
invert(node.left);
invert(node.right);
}
}
| RuchiDeshmukh/leetcode100 | 2.java |
873 | class Solution {
public String mergeAlternately(String word1, String word2) {
int m = word1.length(), n = word2.length();
int i = 0, j = 0;
StringBuilder ans = new StringBuilder();
while (i < m || j < n) {
if (i < m) {
ans.append(word1.charAt(i));
++i;
}
if (j < n) {
ans.append(word2.charAt(j));
++j;
}
}
return ans.toString();
}
}
| peichenc24/leetcode | 1023.java |
874 | class Solution {
public double findMaxAverage(int[] nums, int k) {
int windowOpening = 0;
int sum = 0;
int max = Integer.MIN_VALUE;
for(int i = 0; i < nums.length; i++) {
sum += nums[i];
if(i >= k - 1) {
max = Math.max(max, sum);
sum -= nums[windowOpening++];
}
}
return (double)max/k;
}
}
| subhagittu/Leetcode | max_average_subarray.java |
875 | class Solution {
class Project implements Comparable<Project> {
int capital, profit;
public Project(int capital, int profit) {
this.capital = capital;
this.profit = profit;
}
public int compareTo(Project project) {
return capital - project.capital;
}
}
public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
int n = profits.length;
Project[] projects = new Project[n];
for (int i = 0; i < n; i++) {
projects[i] = new Project(capital[i], profits[i]);
}
Arrays.sort(projects);
// PriorityQueue is a min heap, but we need a max heap, so we use
// Collections.reverseOrder()
PriorityQueue<Integer> q = new PriorityQueue<Integer>(n, Collections.reverseOrder());
int ptr = 0;
for (int i = 0; i < k; i++) {
while (ptr < n && projects[ptr].capital <= w) {
q.add(projects[ptr++].profit);
}
if (q.isEmpty()) {
break;
}
w += q.poll();
}
return w;
}
}
| sanskar6525/Leet-Code-Solutions | my-folder/0502-ipo/solution.java |
876 | /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode tail = dummyHead;
int carry = 0;
while (l1 != null || l2 != null || carry != 0) {
int digit1 = (l1 != null) ? l1.val : 0;
int digit2 = (l2 != null) ? l2.val : 0;
int sum = digit1 + digit2 + carry;
int digit = sum % 10;
carry = sum / 10;
ListNode newNode = new ListNode(digit);
tail.next = newNode;
tail = tail.next;
l1 = (l1 != null) ? l1.next : null;
l2 = (l2 != null) ? l2.next : null;
}
ListNode result = dummyHead.next;
dummyHead.next = null;
return result;
}
}
| uaayush01/LeetCode-- | Add two Numbers |
877 | // Lecture 9 - For Loops
System.out.printf("The value of i is: %d", i);
// replace %d by the value of the integer, as defined by i (after the comma). Prints out everything on one line! Omit by a blank System.out.println();. Or by \n:
System.out.printf("The value of i is: %d\n", i);
System.out.println("The value of i is: " + i);
i++ // i = i + 1"
i < 5; // will return true until.."
i = 0; // starting point"
public class Application {
main static void main(String[] args) {
for(int i = 0; i < 5; i++) {
System.out.println("Hello");
}
}
}
| FloorD/java_notes | 9.java |
878 | import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class C extends Canvas {
private static final long serialVersionUID = 1480902466428347458L;
private static final int WIDTH = 400;
private static final int HEIGHT = 400;
private static final int RANGE = 30;
private static final int INTERVAL = 5;
private double[][] values = new double[WIDTH][HEIGHT];
private double inertia = 0.8;
private double decay = 0.9995;
private double dissipation = 0.92;
@Override
public void paint(Graphics g) {
super.paint(g);
for (int x = 0; x < WIDTH; x++) {
for (int y = 0; y < HEIGHT; y++) {
values[x][y] = 0.0;
g.setColor(color(values[x][y]));
g.drawLine(x, y, x, y);
}
}
int lastX = -1;
int lastY = -1;
int lastT = -1;
while (true) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Probability of rain-drop, should yield < 50/INTERVAL drops per second
if (Math.random() < 1.0/INTERVAL) {
lastX = (int) (Math.random() * WIDTH);
lastY = (int) (Math.random() * HEIGHT);
lastT = 0;
}
else if (lastT >= 3) {
lastX = -100;
}
lastT++;
double[][] newValues = computeNewValues(lastX, lastY);
for (int x = 0; x < WIDTH; x++) {
for (int y = 0; y < HEIGHT; y++) {
g.setColor(color(values[x][y]));
g.drawLine(x, y, x, y);
}
}
values = newValues;
}
}
private double[][] computeNewValues(int lastX, int lastY) {
double[][] newValues = new double[WIDTH][HEIGHT];
for (int i = 0; i < WIDTH; i++) {
for (int j = 0; j < HEIGHT; j++) {
double value = 0.0;
int count = 0;
double dist = Math.sqrt(Math.pow(Math.abs(i - lastX), 2) + Math.pow(Math.abs(j - lastY), 2));
if (dist < RANGE) {
double newValue = 1.0;
while (dist-- > 0) newValue *= dissipation;
newValue = Math.max(newValue, values[i][j]);
value = inertia * values[i][j] + (1 - inertia) * newValue;
} else {
for (int x = i - 5; x <= i + 5; x++) {
for (int y = j - 5; y <= j + 5; y++) {
if (x < 0 || y < 0 || x >= WIDTH || y >= HEIGHT)
continue;
value += values[x][y];
count++;
}
}
value /= count;
}
newValues[i][j] = value * decay;
}
}
return newValues;
}
private float fromValue(double value) {
return (float) (((300 * (1.0 - value) + 300) % 360) / 360.0);
}
private Color color(double value) {
return Color.getHSBColor(fromValue(value), 1.0f, .5f);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(WIDTH, HEIGHT);
frame.add(new C());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
} | tiffanypie/ECS189E | C.java |
880 | import java.util.Arrays;
class Solution {
public int maximumProduct(int[] nums) {
Arrays.sort(nums);
int n = nums.length - 1;
int a = nums[0] * nums[1] * nums[n];
int b = nums[n] * nums[n - 1] * nums[n - 2];
return Math.max(a, b);
}
}
| astro1sumit/leetcodechallenge | 628 |
881 | import javax.swing.*;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
public class G extends JPanel {
int[] coordinates = {100, 20};
int mar = 50;
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new G());
frame.setSize(400, 400);
frame.setLocation(200, 200);
frame.setVisible(true);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g1 = (Graphics2D) g;
g1.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int width = getWidth();
int height = getHeight();
g1.draw(new Line2D.Double(mar, mar, mar, height - mar));
g1.draw(new Line2D.Double(mar, height - mar, width - mar, height - mar));
double x = (double) (width - 2 * mar) / (coordinates.length - 1);
double scale = (double) (height - 2 * mar) / getMax();
g1.setPaint(Color.BLUE);
for (int i = 0; i < coordinates.length; i++) {
double x1 = mar + i * x;
double y1 = height - mar - scale * coordinates[i];
g1.fill(new Ellipse2D.Double(x1 - 2, y1 - 2, 4, 4));
}
}
private int getMax() {
int max = -Integer.MAX_VALUE;
for (int i = 0; i < coordinates.length; i++) {
if (coordinates[i] > max)
max = coordinates[i];
}
return max;
}
}
| k2s09/javaC0de | G.java |
882 | class Solution {
public boolean isPalindrome(int x) {
// if (x < 0){
// return false;
// }
char[] y = Integer.toString(x).toCharArray();
for (int i = 0; i < y.length / 2; i++){
if (y[i] != y[y.length - 1 - i]){
return false;
}
}
return true;
}
} | leungt30/leetcode | 9.java |
883 | // LeetCode 2 Add Two Numbers
// References: https://leetcode.com/problems/add-two-numbers/solutions/3675747/beats-100-c-java-python-beginner-friendly/?envType=study-plan-v2&envId=top-interview-150
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode tail = dummyHead;
int carry = 0;
while (l1 != null || l2 != null || carry != 0){
int digit1 = (l1 != null) ? l1.val : 0;
int digit2 = (l2 != null) ? l2.val : 0;
int sum = digit1 + digit2 + carry;
int digit = sum % 10;
carry = sum / 10;
ListNode newNode = new ListNode(digit);
tail.next = newNode;
tail = tail.next;
l1 = (l1 != null) ? l1.next : null;
l2 = (l2 != null) ? l2.next : null;
}
ListNode result = dummyHead.next;
dummyHead.next = null;
return result;
}
} | ElsaYilinWang/LeetCode | 2.java |
884 | /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int size = 0;
ListNode temp = head;
while(temp!=null){
temp = temp.next;
size++;
}
if(size==n){
return head.next;
}
int pos = size-n;
int cp = 1;
ListNode cur = head;
while(cp!=pos){
cur = cur.next;
cp++;
}
cur.next = cur.next.next;
return head;
}
}
| goswamishipra15/Code-by-Shipra | 3.java |
886 | /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head==null) return null;
while(head!=null && head.val==val)
head = head.next;
ListNode cur = head;
while(cur!=null && cur.next!=null)
{
if(cur.next.val==val)
cur.next = cur.next.next;
else
cur = cur.next;
}
return head;
}
}
| goswamishipra15/Code-by-Shipra | 5.java |
888 | class Solution {
private int[] findLengthPal(String s, int i, int j, int[] res) {
if (i < 0 || j < 0 || i >= s.length() || j >= s.length() || s.charAt(i) != s.charAt(j)) return res;
res[0] = j-i+1;
res[1] = i;
res[2] = j;
return findLengthPal(s, i-1, j+1, res);
}
public String longestPalindrome(String s) {
int[] maxRes = new int[3];
for (int i = 0; i < s.length(); i++) {
int[] res = new int[3];
res = findLengthPal(s, i, i, res);
if (res[0] > maxRes[0]) {
maxRes = res.clone();
}
res = findLengthPal(s, i, i+1, res);
if (res[0] > maxRes[0]) {
maxRes = res.clone();
}
}
return s.substring(maxRes[1], maxRes[2]+1);
}
} | jdolphin5/leetcode | 5.java |
889 | class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i=0; i < nums.length ; i++){
for(int j=i+1; j < nums.length; j++){
if(nums[j] == target - nums[i]){
return new int[] {i,j};
}
}
}
return null;
}
}
| swetaagarwal123/leetcode | 1.java |
890 | class Solution {
public int equalSubstring(String s, String t, int maxCost) {
int N = s.length();
int maxLen = 0;
// Starting index of the current substring
int start = 0;
// Cost of converting the current substring in s to t
int currCost = 0;
for (int i = 0; i < N; i++) {
// Add the current index to the substring
currCost += Math.abs(s.charAt(i) - t.charAt(i));
// Remove the indices from the left end till the cost becomes less than allowed
while (currCost > maxCost) {
currCost -= Math.abs(s.charAt(start) - t.charAt(start));
start++;
}
maxLen = Math.max(maxLen, i - start + 1);
}
return maxLen;
}
}
| akshaykumar7591/Leetcode_Daily_Challenges_Solution | LeetCode_Daily_Question_Solution/1208. Get Equal Substrings Within Budget |
891 | Find winner of game
class Solution {
public String tictactoe(int[][] moves) {
LinkedList<String> list1 = new LinkedList<>();
for (int i = (moves.length % 2 == 0)? 1 : 0; i < moves.length; i += 2)
{
list1.add(moves[i][0] + "" + moves[i][1]);
}
if (
(list1.contains("00") && list1.contains("11") && list1.contains("22"))
|| (list1.contains("02") && list1.contains("11") && list1.contains("20"))
|| (list1.contains("00") && list1.contains("10") && list1.contains("20"))
|| (list1.contains("01") && list1.contains("11") && list1.contains("21"))
|| (list1.contains("02") && list1.contains("12") && list1.contains("22"))
|| (list1.contains("00") && list1.contains("01") && list1.contains("02"))
|| (list1.contains("10") && list1.contains("11") && list1.contains("12"))
|| (list1.contains("20") && list1.contains("21") && list1.contains("22"))
) {
return (moves.length % 2 == 0) ? "B" : "A";
}
return (moves.length == 9)? "Draw" :"Pending";
}
} | GeekyCoder1901/Java-from-scratch | 3.java |
894 | import java.lang.reflect.Method;
class Printer {
<T> void printArray(T[] array) {
for (T element : array) {
System.out.println(element);
}
}
}
public class Solution {
public static void main(String args[]) {
Printer myPrinter = new Printer();
Integer[] intArray = { 1, 2, 3 };
String[] stringArray = { "Hello", "World" };
myPrinter.printArray(intArray);
myPrinter.printArray(stringArray);
int count = 0;
for (Method method : Printer.class.getDeclaredMethods()) {
String name = method.getName();
if (name.equals("printArray"))
count++;
}
if (count > 1)
System.out.println("Method overloading is not allowed!");
assert count == 1;
}
}
| khoahuong/hackerrank | java-generics/Solution.java |
895 | package demo1;
public class one {
public static void main(String[] args) {
System.out.println("Bennett university");
System.out.println("\nCSE");
}
} | dharmanshu9930/Java | 1.java |
896 | //1. Two Sum
// Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// You can return the answer in any order.
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer,Integer> mappings = new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++) {
int cur = nums[i];
if(mappings.containsKey(target-cur)) {
result[0] = i;
result[1] = mappings.get(target-cur);
return result;
}
mappings.put(nums[i],i);
}
return result;
}
}
| jackgopack4/leetcode | 1.java |
898 | package week_1;
import static input.InputUtils.doubleInput;
/**
To become a NASA astronaut, you need to be between 58 and 76 inches tall, so you
are not too tall to fit in the spaceship, but are tall enough to reach all the controls.
You also need to be able to swim at least 75 yards, in case you make a water
landing on your return to earth.
This program asks the user questions about their height and swimming ability.
It calls a method to check if the user meets NASA's requirements.
Finish the checkAstronautQualifications method by writing conditional statements
to determine if the user has potential as a NASA astronaut. The method will return true or false.
There are many ways of doing this too - once you've written and tested a solution,
can you think of another way of doing it? Make sure your tests still pass.
*/
public class Question_3_NASA_Astronauts {
public static void main(String[] args) {
double height = doubleInput("How tall are you, in inches?");
double swimDistance = doubleInput("How far can you swim, in yards?");
boolean astronautPotential = checkAstronautQualifications(height, swimDistance);
if (astronautPotential) {
System.out.println("You have astronaut potential!");
} else {
System.out.println("Sorry, you don't meet NASA's requirements.");
}
}
public static boolean checkAstronautQualifications(double height, double swimDistance) {
if(75>height>58 && swimDistance>=75) return true
return false;
}
}
| Topher254/lanjava | 3.java |
899 | // https://www.hackerrank.com/challenges/java-stdin-stdout/problem
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("================================");
for(int i=0;i<3;i++)
{
String s1=sc.next();
int x=sc.nextInt();
if(s1.length() > 10)
{
s1 = s1.substring(0, 10);
}
System.out.printf("%-15s%03d%n",s1,x);
}
System.out.println("================================");
}
}
| haytastan/Hackerrank_Java | 5.java |
901 | /*---
iGeo - http://igeo.jp
Copyright (c) 2002-2013 Satoru Sugihara
This file is part of iGeo.
iGeo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, version 3.
iGeo is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with iGeo. If not, see <http://www.gnu.org/licenses/>.
---*/
package igeo;
/**
Instantiable class of ISwitchE interface to be used as to switch methods to return entity instance.
@see ISwitchE
@author Satoru Sugihara
*/
public class Ie implements ISwitchE{
public static final Ie i=new Ie();
}
| sghr/iGeo | Ie.java |
902 | package org.fleen.geom_Kisrhombille;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.fleen.geom_2D.GD;
/*
* KISRHOMBILLE GEOMETRY
*
* General kisrhombille coordinate system constants and methods.
*
* Directions are integers. We have 12, like a clock.
* Vertex has 4 coordinates. TODO reduce to 3
*
*
*
* o V12
* |\
* | \
* | \
* | \ hawk
* goat | \
* | \
* | \
* | \
* V4 o--------o V6
* fish
*
*/
public class GK{
public static final double SQRT3=Math.sqrt(3.0);
public static final int AXISCOUNT=6;
/*
* ################################
* BASIC DIAMOND CONSTANTS AND METRICS
* ################################
*/
public static final boolean
TWIST_POSITIVE=true,
TWIST_NEGATIVE=false;
public static enum Orbit{
CLOCKWISE,
COUNTERCLOCKWISE}
/*
* ++++++++++++++++++++++++++++++++
* VERTEX TYPES
* type values corrospond to dog values
* name index corrosponds to the number of segs that connect at a vertex of that type
* eg : VERTEX12 has 12 connections, VERTEX4A has 4 connections, etc
*/
public static final int
VERTEX_NULL=-1,
VERTEX_12=0,
VERTEX_4A=1,
VERTEX_6A=2,
VERTEX_4B=3,
VERTEX_6B=4,
VERTEX_4C=5;
/*
* ++++++++++++++++++++++++++++++++
* VERTEX GENERAL TYPES
* general type is 4,6 or 12
* it is also the number of edges at the vertex
*/
public static final int
VERTEX_GTYPE_4=0,
VERTEX_GTYPE_6=1,
VERTEX_GTYPE_12=2;
/*
* ++++++++++++++++++++++++++++++++
* EDGE TYPES
* "edge" as in a graph edge
* that is, the connecting lines between vertices
*/
public static final int
EDGE_NULL=-1,EDGE_FISH=0,EDGE_GOAT=1,EDGE_HAWK=2;
/*
* ++++++++++++++++++++++++++++++++
* EDGE STANDARD LENGTH VALUES
* these can be scaled however, of course
*/
public static final double
EDGESLV_FISH=1.0,
EDGESLV_GOAT=Math.sqrt(3.0),
EDGESLV_HAWK=2.0;
/*
* ++++++++++++++++++++++++++++++++
* DIRECTIONS
* For standard grid spin (spin==true) DIRECTION_0 is north and
* they are addressed clockwise.
*/
public static final int
DIRECTION_NULL=-1,
DIRECTION_0=0,
DIRECTION_1=1,
DIRECTION_2=2,
DIRECTION_3=3,
DIRECTION_4=4,
DIRECTION_5=5,
DIRECTION_6=6,
DIRECTION_7=7,
DIRECTION_8=8,
DIRECTION_9=9,
DIRECTION_10=10,
DIRECTION_11=11;
/*
* ++++++++++++++++++++++++++++++++
* 2D VALUES FOR OUR 12 DIRECTIONS
*/
public static final double[] DIRECTION_2D={
(0.0/12.0)*(GD.PI*2.0),
(1.0/12.0)*(GD.PI*2.0),
(2.0/12.0)*(GD.PI*2.0),
(3.0/12.0)*(GD.PI*2.0),
(4.0/12.0)*(GD.PI*2.0),
(5.0/12.0)*(GD.PI*2.0),
(6.0/12.0)*(GD.PI*2.0),
(7.0/12.0)*(GD.PI*2.0),
(8.0/12.0)*(GD.PI*2.0),
(9.0/12.0)*(GD.PI*2.0),
(10.0/12.0)*(GD.PI*2.0),
(11.0/12.0)*(GD.PI*2.0)};
/*
* convert diamond direction to real 2d direciton
*/
public static final double getDirection2D(int d){
if(d<0||d>11)return -1;
return DIRECTION_2D[d];}
/*
* Direction axis types
*/
public static final boolean
DIRECTION_AXIS_HAWK=true,
DIRECTION_AXIS_GOAT=false;
/*
*
*/
public static final boolean getAxisType(int d){
return d%2==0;}
public static final boolean directionAxisIsHawky(int d){
return d%2==0;}
public static final boolean directionAxisIsGoaty(int d){
return d%2==1;}
/*
* normalize arbitrary integer value to range [0,11]
*/
public static final int normalizeDirection(int d){
d=d%12;
if(d<0)d+=12;
return d;}
/*
* ################################
* VERTEX LIBERTIES
* each vertex is connected to the diamond graph via 4, 6 or 12 directions.
* We refer to each of directions as a "liberty".
* herein we describe the set of liberties for each vertex type (indicated by the "dog" coordinate)
* ################################
*/
public static final int[][] VERTEX_LIBERTIES={
{0,1,2,3,4,5,6,7,8,9,10,11},//V12
{2,5,8,11},//V4A
{0,2,4,6,8,10},//V6A
{1,4,7,10},//V4B
{0,2,4,6,8,10},//V6B
{0,3,6,9}};//V4C
public static final int[] getLiberties(int vdog){
return VERTEX_LIBERTIES[vdog];}
/*
* return true if a vertex of the specified type (vdog)
* has liberty in the specified direction.
* false otherwise.
*/
public static final boolean hasLiberty(int vdog,int dir){
for(int i=0;i<VERTEX_LIBERTIES[vdog].length;i++){
if(VERTEX_LIBERTIES[vdog][i]==dir)
return true;}
return false;}
/*
* ################################
* ADJACENT VERTEX
* ################################
*/
/*
* returns null if the specified vertex has no such adjacent in the specified direction
*/
public static final KPoint getVertex_Adjacent(KPoint v,int dir){
int[] v1=new int[4];
getVertex_Adjacent(
v.coors[0],
v.coors[1],
v.coors[2],
v.coors[3],
dir,
v1);
if(v1[3]==VERTEX_NULL)return null;
return new KPoint(v1);}
/*
* Given the specified vertex (v0a,v0b,v0c,v0d) and a direction (dir), return
* the coordinates of the implied adjacent vertex in the v1 array
* if the specified direction indicates an invalid liberty for v0
* then we return VERTEX_NULL in v1[3]
*/
public static final void getVertex_Adjacent(int v0a,int v0b,int v0c,int v0d,int dir,int[] v1){
switch(v0d){
case VERTEX_12:
switch(dir){
case DIRECTION_0:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=2;
return;
case DIRECTION_1:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=3;
return;
case DIRECTION_2:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=4;
return;
case DIRECTION_3:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=5;
return;
case DIRECTION_4:
v1[0]=v0a+1;
v1[1]=v0b;
v1[2]=v0c-1;
v1[3]=2;
return;
case DIRECTION_5:
v1[0]=v0a+1;
v1[1]=v0b;
v1[2]=v0c-1;
v1[3]=1;
return;
case DIRECTION_6:
v1[0]=v0a;
v1[1]=v0b-1;
v1[2]=v0c-1;
v1[3]=4;
return;
case DIRECTION_7:
v1[0]=v0a;
v1[1]=v0b-1;
v1[2]=v0c-1;
v1[3]=3;
return;
case DIRECTION_8:
v1[0]=v0a;
v1[1]=v0b-1;
v1[2]=v0c-1;
v1[3]=2;
return;
case DIRECTION_9:
v1[0]=v0a-1;
v1[1]=v0b-1;
v1[2]=v0c;
v1[3]=5;
return;
case DIRECTION_10:
v1[0]=v0a-1;
v1[1]=v0b-1;
v1[2]=v0c;
v1[3]=4;
return;
case DIRECTION_11:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=1;
return;
default:
v1[3]=VERTEX_NULL;
return;}
case VERTEX_4A:
switch(dir){
case DIRECTION_2:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=2;
return;
case DIRECTION_5:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=0;
return;
case DIRECTION_8:
v1[0]=v0a-1;
v1[1]=v0b-1;
v1[2]=v0c;
v1[3]=4;
return;
case DIRECTION_11:
v1[0]=v0a-1;
v1[1]=v0b;
v1[2]=v0c+1;
v1[3]=0;
return;
default:
v1[3]=VERTEX_NULL;
return;}
case VERTEX_6A:
switch(dir){
case DIRECTION_0:
v1[0]=v0a-1;
v1[1]=v0b;
v1[2]=v0c+1;
v1[3]=5;
return;
case DIRECTION_2:
v1[0]=v0a;
v1[1]=v0b+1;
v1[2]=v0c+1;
v1[3]=0;
return;
case DIRECTION_4:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=3;
return;
case DIRECTION_6:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=0;
return;
case DIRECTION_8:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=1;
return;
case DIRECTION_10:
v1[0]=v0a-1;
v1[1]=v0b;
v1[2]=v0c+1;
v1[3]=0;
return;
default:
v1[3]=VERTEX_NULL;
return;}
case VERTEX_4B:
switch(dir){
case DIRECTION_1:
v1[0]=v0a;
v1[1]=v0b+1;
v1[2]=v0c+1;
v1[3]=0;
return;
case DIRECTION_4:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=4;
return;
case DIRECTION_7:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=0;
return;
case DIRECTION_10:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=2;
return;
default:
v1[3]=VERTEX_NULL;
return;}
case VERTEX_6B:
switch(dir){
case DIRECTION_0:
v1[0]=v0a;
v1[1]=v0b+1;
v1[2]=v0c+1;
v1[3]=0;
return;
case DIRECTION_2:
v1[0]=v0a+1;
v1[1]=v0b+1;
v1[2]=v0c;
v1[3]=1;
return;
case DIRECTION_4:
v1[0]=v0a+1;
v1[1]=v0b+1;
v1[2]=v0c;
v1[3]=0;
return;
case DIRECTION_6:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=5;
return;
case DIRECTION_8:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=0;
return;
case DIRECTION_10:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=3;
return;
default:
v1[3]=VERTEX_NULL;
return;}
case VERTEX_4C:
switch(dir){
case DIRECTION_0:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=4;
return;
case DIRECTION_3:
v1[0]=v0a+1;
v1[1]=v0b+1;
v1[2]=v0c;
v1[3]=0;
return;
case DIRECTION_6:
v1[0]=v0a+1;
v1[1]=v0b;
v1[2]=v0c-1;
v1[3]=2;
return;
case DIRECTION_9:
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=0;
return;
default:
v1[3]=VERTEX_NULL;
return;}
default:
v1[3]=VERTEX_NULL;
return;}}
/*
* ################################
* VERTEX EDGE TYPES BY DIRECTION
* ################################
*/
/*
* Given a vertex type (vdog) and a direction (dir), get the edge type therein
*/
public static final int getEdgeType(int vdog,int dir){
switch(vdog){
case VERTEX_12:
switch(dir){
case DIRECTION_0:
return EDGE_HAWK;
case DIRECTION_1:
return EDGE_GOAT;
case DIRECTION_2:
return EDGE_HAWK;
case DIRECTION_3:
return EDGE_GOAT;
case DIRECTION_4:
return EDGE_HAWK;
case DIRECTION_5:
return EDGE_GOAT;
case DIRECTION_6:
return EDGE_HAWK;
case DIRECTION_7:
return EDGE_GOAT;
case DIRECTION_8:
return EDGE_HAWK;
case DIRECTION_9:
return EDGE_GOAT;
case DIRECTION_10:
return EDGE_HAWK;
case DIRECTION_11:
return EDGE_GOAT;
default:
return EDGE_NULL;}
case VERTEX_4A:
switch(dir){
case DIRECTION_2:
return EDGE_FISH;
case DIRECTION_5:
return EDGE_GOAT;
case DIRECTION_8:
return EDGE_FISH;
case DIRECTION_11:
return EDGE_GOAT;
default:
return EDGE_NULL;}
case VERTEX_6A:
switch(dir){
case DIRECTION_0:
return EDGE_FISH;
case DIRECTION_2:
return EDGE_HAWK;
case DIRECTION_4:
return EDGE_FISH;
case DIRECTION_6:
return EDGE_HAWK;
case DIRECTION_8:
return EDGE_FISH;
case DIRECTION_10:
return EDGE_HAWK;
default:
return EDGE_NULL;}
case VERTEX_4B:
switch(dir){
case DIRECTION_1:
return EDGE_GOAT;
case DIRECTION_4:
return EDGE_FISH;
case DIRECTION_7:
return EDGE_GOAT;
case DIRECTION_10:
return EDGE_FISH;
default:
return EDGE_NULL;}
case VERTEX_6B:
switch(dir){
case DIRECTION_0:
return EDGE_HAWK;
case DIRECTION_2:
return EDGE_FISH;
case DIRECTION_4:
return EDGE_HAWK;
case DIRECTION_6:
return EDGE_FISH;
case DIRECTION_8:
return EDGE_HAWK;
case DIRECTION_10:
return EDGE_FISH;
default:
return EDGE_NULL;}
case VERTEX_4C:
switch(dir){
case DIRECTION_0:
return EDGE_FISH;
case DIRECTION_3:
return EDGE_GOAT;
case DIRECTION_6:
return EDGE_FISH;
case DIRECTION_9:
return EDGE_GOAT;
default:
return EDGE_NULL;}
default:
return EDGE_NULL;}}
/*
* ################################
* VERTEX, VECTOR, DISTANCE, DIRECTION OPS
* NOTE We don't have to be really optimal or efficient, so we arent. We brute it.
* We will be dealing with distances in the range of 1..20 at most.
* More likely maxing at 5. We do it the easy way. Prolly the faster way too.
* Look at the old code for our old bloated complex universally applicable methods.
* ################################
*/
/**
* Given 2 directions, get the direction of d0 relative to d1
* returns value in range [-5,5]
* throws exception on direction reversal
* TODO just return the -6?
*/
public static final int getDirectionDelta(int d0,int d1){
int delta;
if(d0==d1){//same direction
delta=0;
}else{
//pretend that d0 is 0
int w=(d1+12-d0)%12;
if(w<6){
delta=w;
}else if(w>6){
delta=w-12;
}else{
throw new IllegalArgumentException("BAD GEOMETRY : direction reversal : d0="+d0+" d1="+d1);}}
return delta;}
/*
* ++++++++++++++++++++++++++++++++
* GET DIRECTION VERTEX VERTEX
* ++++++++++++++++++++++++++++++++
*/
private static final double
GETDIRVV_ERROR=1.0/(65596.0*2.0*GD.PI),
DIRECTION_2D_0_ALTERNATE=GD.PI*2.0;
private static final double[][] GETDIRVV_RANGES={
{DIRECTION_2D_0_ALTERNATE-GETDIRVV_ERROR,GETDIRVV_ERROR},
{DIRECTION_2D[1]-GETDIRVV_ERROR,DIRECTION_2D[1]+GETDIRVV_ERROR},
{DIRECTION_2D[2]-GETDIRVV_ERROR,DIRECTION_2D[2]+GETDIRVV_ERROR},
{DIRECTION_2D[3]-GETDIRVV_ERROR,DIRECTION_2D[3]+GETDIRVV_ERROR},
{DIRECTION_2D[4]-GETDIRVV_ERROR,DIRECTION_2D[4]+GETDIRVV_ERROR},
{DIRECTION_2D[5]-GETDIRVV_ERROR,DIRECTION_2D[5]+GETDIRVV_ERROR},
{DIRECTION_2D[6]-GETDIRVV_ERROR,DIRECTION_2D[6]+GETDIRVV_ERROR},
{DIRECTION_2D[7]-GETDIRVV_ERROR,DIRECTION_2D[7]+GETDIRVV_ERROR},
{DIRECTION_2D[8]-GETDIRVV_ERROR,DIRECTION_2D[8]+GETDIRVV_ERROR},
{DIRECTION_2D[9]-GETDIRVV_ERROR,DIRECTION_2D[9]+GETDIRVV_ERROR},
{DIRECTION_2D[10]-GETDIRVV_ERROR,DIRECTION_2D[10]+GETDIRVV_ERROR},
{DIRECTION_2D[11]-GETDIRVV_ERROR,DIRECTION_2D[11]+GETDIRVV_ERROR}};
/*
* Given 2 vertices : v0,v1
* get the direction from v0 to v1
* If the direction is invalid because the 2 vertices are not colinar (coaxial)
* (not one of our 12, within error) then we return DIRECTION_NULL
*/
public static final int getDirection_VertexVertex(
int v0a,int v0b,int v0c,int v0d,int v1a,int v1b,int v1c,int v1d){
//get the direction 2dwise
double[] p0=new double[2],p1=new double[2];
getBasicPoint2D_Vertex(v0a,v0b,v0c,v0d,p0);
getBasicPoint2D_Vertex(v1a,v1b,v1c,v1d,p1);
double d2d=GD.getDirection_PointPoint(p0[0],p0[1],p1[0],p1[1]);
double[] range;
//filter the 2d direction value for gkis direction 0
if(d2d>GETDIRVV_RANGES[0][0]||d2d<GETDIRVV_RANGES[0][1])
return 0;
//filter the 2d direction value for our other 11 gkis directions
for(int i=1;i<12;i++){
range=GETDIRVV_RANGES[i];
if(d2d>range[0]&&d2d<range[1])
return i;}
return DIRECTION_NULL;}
public static final int getDirection_VertexVertex(KPoint v0,KPoint v1){
return getDirection_VertexVertex(
v0.getAnt(),v0.getBat(),v0.getCat(),v0.getDog(),
v1.getAnt(),v1.getBat(),v1.getCat(),v1.getDog());}
// public static final void main(String[] a){
// KVertex v0=new KVertex(-1,2,3,0),v1=new KVertex(-1,1,2,2);
// int dir=getDirection_VertexVertex(v0,v1);
// System.out.println("dir="+dir);
// }
/*
* COLINEARITY TEST
* If the direction from v0 to v1 is a valid one for that particular
* pair of vertex types then v0 and v1 are colinear.
*/
public static final boolean getColinear_VertexVertex(
int v0a,int v0b,int v0c,int v0d,int v1a,int v1b,int v1c,int v1d){
int d=getDirection_VertexVertex(v0a,v0b,v0c,v0d,v1a,v1b,v1c,v1d);
//if null direction then noncolinear
if(d==DIRECTION_NULL)return false;
//we have a valid direction, is it valid for this pair of vertex types?
//that is, is it a shared liberty?
return hasLiberty(v0d,d)&&hasLiberty(v1d,d);}
/*
* ++++++++++++++++++++++++++++++++
* GET DISTANCE VERTEX VERTEX
* simply convert to basic 2d points and use 2d distance
* ++++++++++++++++++++++++++++++++
*/
public static final double getDistance_VertexVertex(
KPoint v0,KPoint v1){
return getDistance_VertexVertex(
v0.getAnt(),v0.getBat(),v0.getCat(),v0.getDog(),
v1.getAnt(),v1.getBat(),v1.getCat(),v1.getDog());}
public static final double getDistance_VertexVertex(
int v0a,int v0b,int v0c,int v0d,int v1a,int v1b,int v1c,int v1d){
double[] p0=new double[2],p1=new double[2];
getBasicPoint2D_Vertex(v0a,v0b,v0c,v0d,p0);
getBasicPoint2D_Vertex(v1a,v1b,v1c,v1d,p1);
return GD.getDistance_PointPoint(p0[0],p0[1],p1[0],p1[1]);}
/*
* ++++++++++++++++++++++++++++++++
* GET VECTOR FROM 2 VERTICES
* ++++++++++++++++++++++++++++++++
*/
public static final KVector getVector_VertexVertex(
int v0a,int v0b,int v0c,int v0d,int v1a,int v1b,int v1c,int v1d){
int dir=getDirection_VertexVertex(v0a,v0b,v0c,v0d,v1a,v1b,v1c,v1d);
//if it's a null direction then bad vector
if(dir==DIRECTION_NULL)return null;
//if the direction is one where either of the vertices has no such liberty then bad vector
if(!(hasLiberty(v0d,dir))&&(hasLiberty(v1d,dir)))return null;
//get distance and that's that
double dis=getDistance_VertexVertex(v0a,v0b,v0c,v0d,v1a,v1b,v1c,v1d);
return new KVector(dir,dis);}
/*
* ++++++++++++++++++++++++++++++++
* GET VERTEX FROM VERTEX AND VECTOR
* Crawl from the specified vertex one adjacent neighbor at a time in
* the specified direction over the specified distance until distance is within error of zero
* if it falls beneath negative error then fail.
* ++++++++++++++++++++++++++++++++
*/
private static final double
GETVERTEXVV_TRAVERSALERRORCEILING=1.0/65536.0,
GETVERTEXVV_TRAVERSALERRORFLOOR=-GETVERTEXVV_TRAVERSALERRORCEILING;
public static final KPoint getVertex_VertexVector(KPoint v,KVector t){
int[] v1=new int[4];
getVertex_VertexVector(v.getAnt(),v.getBat(),v.getCat(),v.getDog(),t.direction,t.distance,v1);
if(v1[3]==VERTEX_NULL)return null;
KPoint vertex=new KPoint(v1);
return vertex;}
public static final int[] getVertex_VertexVector(int[] v0,int tdir,double tdis){
int[] v1=new int[4];
getVertex_VertexVector(v0[0],v0[1],v0[2],v0[3],tdir,tdis,v1);
return v1;}
/*
* return the vertex in v1 as an int[4] of coordinates
* return VERTEX_NULL at dog on fail
*/
public static final void getVertex_VertexVector(
int v0a,int v0b,int v0c,int v0d,int tdir,double tdis,int[] v1){
double remaining=tdis;
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=v0d;
while(remaining>GETVERTEXVV_TRAVERSALERRORCEILING){
remaining-=getAdjacentDistance(v1[3],tdir);
if(remaining<GETVERTEXVV_TRAVERSALERRORFLOOR){
v1[3]=VERTEX_NULL;
return;}
getVertex_Adjacent(v1[0],v1[1],v1[2],v1[3],tdir,v1);
if(v1[3]==VERTEX_NULL){
return;}}}
/*
* given the specified vertex type and direction, get the distance to the vertex adjacent to
* that vertex in that direction.
* we DO NOT check that a vertex with the specified vdog does indeed have a liberty at the specified direction
* so if the specified vertex type does not have a liberty at the specified direction then an ambiguous value
* will be returned
*/
public static final double getAdjacentDistance(int vdog,int dir){
if(dir%2==1)return EDGESLV_GOAT;
switch(vdog){
case VERTEX_12:
return EDGESLV_HAWK;
case VERTEX_4A:
return EDGESLV_FISH;
case VERTEX_6A:
if(dir%4==0){
return EDGESLV_FISH;
}else{
return EDGESLV_HAWK;}
case VERTEX_4B:
return EDGESLV_FISH;
case VERTEX_6B:
if(dir%4==0){
return EDGESLV_HAWK;
}else{
return EDGESLV_FISH;}
case VERTEX_4C:
return EDGESLV_FISH;
default:
throw new IllegalArgumentException("invalid value for vdog : "+vdog);}}
/*
* ++++++++++++++++++++++++++++++++
* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
* TEST
* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
* ++++++++++++++++++++++++++++++++
*/
private static final int TEST_CYCLES_COUNT=10000;
/*
* get a random vertex v0
* get a random vector t
* derive v1 via sequential adjacent process
* derive v1 via getVertex_VertexVector method
* if they match then good
* if they don't then fail
* run it 10000 times or so
* time it too
*/
public static final void TEST_getVertex_VertexVector(){
int[] v0,v1a,v1b,vector;
int failurecount=0;
for(int i=0;i<TEST_CYCLES_COUNT;i++){
v0=getRandomVertex();
vector=getRandomVector(v0);
v1a=new int[4];
v1b=new int[4];
getVertex_VertexVector_AdjProcessForTest(v0[0],v0[1],v0[2],v0[3],vector[0],vector[1],v1a);
getVertex_VertexVector(v0[0],v0[1],v0[2],v0[3],vector[0],vector[1],v1b);
//our derived vertices can match in 2 ways :
// 1) they both express failure (dog==VERTEX_NULL therefor invalid vertex, due to bad distance)
// 2) all of the coordinates match
if(
(v1a[3]==VERTEX_NULL&&v1b[3]==VERTEX_NULL)||
(v1a[0]==v1b[0]&&
v1a[1]==v1b[1]&&
v1a[2]==v1b[2]&&
v1a[3]==v1b[3])){
System.out.println("TEST INDEX : "+i+" : --- SUCCEESS ---");
}else{
failurecount++;
System.out.println("TEST INDEX : "+i+" : ##>> FAIL <<##");
System.out.println("v0 : "+v0[0]+","+v0[1]+","+v0[2]+","+v0[3]);
System.out.println("vector dir : "+vector[0]);
System.out.println("vector dis : "+vector[1]);
System.out.println("v1a : "+v1a[0]+","+v1a[1]+","+v1a[2]+","+v1a[3]);
System.out.println("v1b : "+v1b[0]+","+v1b[1]+","+v1b[2]+","+v1b[3]);
System.out.println("#><##><##><##><##><##><##><##><#");}}
//
if(failurecount==0){
System.out.println("^^^^^^^^^^^^^^");
System.out.println("TEST SUCCEEDED");
System.out.println("TEST CYCLES : "+TEST_CYCLES_COUNT);
System.out.println("^^^^^^^^^^^^^^");
}else{
System.out.println("#><##><##><##><##><##><##><##><#");
System.out.println("TEST FAILED");
System.out.println("TEST CYCLES : "+TEST_CYCLES_COUNT);
System.out.println("FAILURE COUNT : "+failurecount);
System.out.println("#><##><##><##><##><##><##><##><#");}}
/*
* consider our vertex and vector
* traverse adjacent vertices from v0 in direction vector.direction until total distance >= vector.distance
* if 0 was skipped and total distance reached is > vector.distance then we have arrived in the middle of a hawk
* edge. Therefor fail because distances must work out perfectly.
*/
private static final void getVertex_VertexVector_AdjProcessForTest(
int v0a,int v0b,int v0c,int v0d,int tdir,int tdis,int[] v1){
int distancetraversed=0,edgelength;
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=v0d;
while(distancetraversed<tdis){
edgelength=(getEdgeType(v1[3],tdir)==EDGE_HAWK)?2:1;
getVertex_Adjacent(v1[0],v1[1],v1[2],v1[3],tdir,v1);
distancetraversed+=edgelength;}
//if we have overrun our vector distance then the vertex is invalid
if(distancetraversed>tdis){
v1[3]=VERTEX_NULL;}}
private static final int[] getRandomVertex(){
Random r=new Random();
int
a=r.nextInt(21)-10,
b=r.nextInt(21)-10,
c=b-a,
d=r.nextInt(6);
return new int[]{a,b,c,d};}
private static final int[] getRandomVector(int[] v){
Random r=new Random();
int
dir=VERTEX_LIBERTIES[v[3]][r.nextInt(VERTEX_LIBERTIES[v[3]].length)],
dis=r.nextInt(33)+1;
return new int[]{dir,dis};}
/*
* ################################
* POINT 2D FROM VERTEX
* Given a basic diamond coordinate system (origin=(0,0), twist=true, foreward=0, fish=1),
* translate the specified diamond vertex coordinates into 2d point coordinates
* ################################
*/
private static final double
UINT_1=1.0,
UINT_2=2.0,
UINT_SQRT3=Math.sqrt(3.0),
P2D_G=UINT_SQRT3/2.0,
P2D_H=3.0/2.0;
public static final double[] getBasicPoint2D_Vertex(int[] p){
double[] p2=new double[2];
getBasicPoint2D_Vertex(p[0],p[1],p[2],p[3],p2);
return p2;}
/*
* return the 2d point assuming a standard diamond grid where
* foreward == 0/2PI, fish=1.0 and direction indexing is clockwise.
*/
public static final void getBasicPoint2D_Vertex(int ant,int bat,int cat,int dog,double[] p2d){
//start with coordinates of the v12 at the center of the flower
p2d[0]=(ant+bat)*UINT_SQRT3;
p2d[1]=cat*(UINT_1+UINT_2);
//the other 5 vertices are relative to the V12
switch(dog){
case 0: //V12
break;
case 1: //V4A
p2d[0]-=P2D_G;
p2d[1]+=P2D_H;
break;
case 2: //V6A
p2d[1]+=UINT_2;
break;
case 3: //V4B
p2d[0]+=P2D_G;
p2d[1]+=P2D_H;
break;
case 4: //V6B
p2d[0]+=UINT_SQRT3;
p2d[1]+=UINT_1;
break;
case 5: //V4C
p2d[0]+=UINT_SQRT3;
break;
default:throw new IllegalArgumentException("dog out of range [0,5]. dog=="+dog);}}
/*
* ################################
* GET VERTEX TRANSITIONWISE
* Use an integer transitions count instead of real distance
* ################################
*/
/*
* ++++++++++++++++++++++++++++++++
* get vertex via vertex, direction and transitions
* ++++++++++++++++++++++++++++++++
*/
//dog patterns by direction
private static final int[]
DOGPATTERN0={0,2,5,4},
DOGPATTERN1={0,3,0,3},
DOGPATTERN2={0,4,1,2},
DOGPATTERN3={0,5,0,5},
DOGPATTERN4={0,2,3,4},
DOGPATTERN5={0,1,0,1},
DOGPATTERN6={0,4,5,2},
DOGPATTERN7={0,3,0,3},
DOGPATTERN8={0,2,1,4},
DOGPATTERN9={0,5,0,5},
DOGPATTERN10={0,4,3,2},
DOGPATTERN11={0,1,0,1};
/*
* given a vertex (v0a,v0b,v0c,v0d) a direction (dir) and a transitions count (trans), return the
* implied vertex coordinates in v1.
*/
public static final void getVertex_Transitionswise(
int v0a,int v0b,int v0c,int v0d,int dir,int trans,int[] v1){
//if transitions is 0 then we return the original vertex
if(trans==0){
v1[0]=v0a;
v1[1]=v0b;
v1[2]=v0c;
v1[3]=v0d;}
//
switch(v0d){
//++++++++++++++++
case VERTEX_12:
switch(dir){
case 0:
v1[0]=v0a-(trans+2)/4;
v1[1]=v0b+trans/4;
v1[2]=v0c+trans/2;
v1[3]=DOGPATTERN0[trans%4];
return;
case 1:
v1[0]=v0a;
v1[1]=v0b+trans/2;
v1[2]=v0c+trans/2;
v1[3]=DOGPATTERN1[trans%4];
return;
case 2:
v1[0]=v0a+(trans+2)/4;
v1[1]=v0b+trans/2;
v1[2]=v0c+trans/4;
v1[3]=DOGPATTERN2[trans%4];
return;
case 3:
v1[0]=v0a+trans/2;
v1[1]=v0b+trans/2;
v1[2]=v0c;
v1[3]=DOGPATTERN3[trans%4];
return;
case 4:
v1[0]=v0a+trans/2;
if(trans%4==1)v1[0]++;
v1[1]=v0b+trans/4;
v1[2]=v0c-(trans+3)/4;
v1[3]=DOGPATTERN4[trans%4];
return;
case 5:
v1[0]=v0a+(trans+1)/2;
v1[1]=v0b;
v1[2]=v0c-(trans+1)/2;
v1[3]=DOGPATTERN5[trans%4];
return;
case 6:
v1[0]=v0a+(trans+1)/4;
v1[1]=v0b-(trans+3)/4;
v1[2]=v0c-(trans+1)/2;
v1[3]=DOGPATTERN6[trans%4];
return;
case 7:
v1[0]=v0a;
v1[1]=v0b-(trans+1)/2;
v1[2]=v0c-(trans+1)/2;
v1[3]=DOGPATTERN7[trans%4];
return;
case 8:
v1[0]=v0a-(trans+1)/4;
v1[1]=v0b-(trans+1)/2;
v1[2]=v0c-(trans+3)/4;
v1[3]=DOGPATTERN8[trans%4];
return;
case 9:
v1[0]=v0a-(trans+1)/2;
v1[1]=v0b-(trans+1)/2;
v1[2]=v0c;
v1[3]=DOGPATTERN9[trans%4];
return;
case 10:
v1[0]=v0a-trans/2;
if(trans%4==1)v1[0]--;
v1[1]=v0b-(trans+3)/4;
v1[2]=v0c+trans/4;
v1[3]=DOGPATTERN10[trans%4];
return;
case 11:
v1[0]=v0a-trans/2;
v1[1]=v0b;
v1[2]=v0c+trans/2;
v1[3]=DOGPATTERN11[trans%4];
return;
//INVALID DIRECTION
default:
return;}
//++++++++++++++++
case VERTEX_4A:
switch(dir){
case 2:
v1[0]=v0a+trans/4;
v1[1]=v0b+trans/2;
v1[2]=v0c+(trans+2)/4;
v1[3]=DOGPATTERN2[(trans+2)%4];
return;
case 5:
v1[0]=v0a+trans/2;
v1[1]=v0b;
v1[2]=v0c-trans/2;
v1[3]=DOGPATTERN5[(trans+1)%4];
return;
case 8:
v1[0]=v0a-(trans+3)/4;
v1[1]=v0b-(trans+1)/2;
v1[2]=v0c-(trans+1)/4;
v1[3]=DOGPATTERN8[(trans+2)%4];
return;
case 11:
v1[0]=v0a-(trans+1)/2;
v1[1]=v0b;
v1[2]=v0c+(trans+1)/2;
v1[3]=DOGPATTERN5[(trans+1)%4];
return;
//INVALID DIRECTION
default:
return;}
//++++++++++++++++
case VERTEX_6A:
switch(dir){
case 0:
v1[0]=v0a-(trans+3)/4;
v1[1]=v0b+(trans+1)/4;
v1[2]=v0c+(trans+1)/2;
v1[3]=DOGPATTERN0[(trans+1)%4];
return;
case 2:
v1[0]=v0a+(trans+1)/4;
v1[1]=v0b+(trans+1)/2;
v1[2]=v0c+(trans+3)/4;
v1[3]=DOGPATTERN2[(trans+3)%4];
return;
case 4:
v1[0]=v0a+trans/2;
if(trans%4==2)v1[0]--;
v1[1]=v0b+(trans+1)/4;
v1[2]=v0c-trans/4;
v1[3]=DOGPATTERN4[(trans+1)%4];
return;
case 6:
v1[0]=v0a+trans/4;
v1[1]=v0b-(trans+2)/4;
v1[2]=v0c-trans/2;
v1[3]=DOGPATTERN6[(trans+3)%4];
return;
case 8:
v1[0]=v0a-(trans+2)/4;
v1[1]=v0b-trans/2;
v1[2]=v0c-trans/4;
v1[3]=DOGPATTERN8[(trans+1)%4];
return;
case 10:
v1[0]=v0a-(trans+1)/2;
if(trans%4==2)v1[0]--;
v1[1]=v0b-(trans+2)/4;
v1[2]=v0c+(trans+3)/4;
v1[3]=DOGPATTERN10[(trans+3)%4];
return;
//INVALID DIRECTION
default:
return;}
//++++++++++++++++
case VERTEX_4B:
switch(dir){
case 1:
v1[0]=v0a;
v1[1]=v0b+(trans+1)/2;
v1[2]=v0c+(trans+1)/2;
v1[3]=DOGPATTERN1[(trans+1)%4];
return;
case 4:
v1[0]=v0a+(trans+1)/2;
if(trans%4==1)v1[0]--;
v1[1]=v0b+(trans+2)/4;
v1[2]=v0c-(trans+1)/4;
v1[3]=DOGPATTERN4[(trans+2)%4];
return;
case 7:
v1[0]=v0a;
v1[1]=v0b-trans/2;
v1[2]=v0c-trans/2;
v1[3]=DOGPATTERN7[(trans+1)%4];
return;
case 10:
v1[0]=v0a-trans/2;
if(trans%4==3)v1[0]--;
v1[1]=v0b-(trans+1)/4;
v1[2]=v0c+(trans+2)/4;
v1[3]=DOGPATTERN10[(trans+2)%4];
return;
//INVALID DIRECTION
default:
return;}
//++++++++++++++++
case VERTEX_6B:
switch(dir){
case 0:
v1[0]=v0a-(trans+1)/4;
v1[1]=v0b+(trans+3)/4;
v1[2]=v0c+(trans+1)/2;
v1[3]=DOGPATTERN0[(trans+3)%4];
return;
case 2:
v1[0]=v0a+(trans+3)/4;
v1[1]=v0b+(trans+1)/2;
v1[2]=v0c+(trans+1)/4;
v1[3]=DOGPATTERN2[(trans+1)%4];
return;
case 4:
v1[0]=v0a+(trans+1)/2;
if(trans%4==2)v1[0]++;
v1[1]=v0b+(trans+3)/4;
v1[2]=v0c-(trans+2)/4;
v1[3]=DOGPATTERN4[(trans+3)%4];
return;
case 6:
v1[0]=v0a+(trans+2)/4;
v1[1]=v0b-trans/4;
v1[2]=v0c-trans/2;
v1[3]=DOGPATTERN6[(trans+1)%4];
return;
case 8:
v1[0]=v0a-trans/4;
v1[1]=v0b-trans/2;
v1[2]=v0c-(trans+2)/4;
v1[3]=DOGPATTERN8[(trans+3)%4];
return;
case 10:
v1[0]=v0a-trans/2;
if(trans%4==2)v1[0]++;
v1[1]=v0b-trans/4;
v1[2]=v0c+(trans+1)/4;
v1[3]=DOGPATTERN10[(trans+1)%4];
return;
//INVALID DIRECTION
default:
return;}
//++++++++++++++++
case VERTEX_4C:
switch(dir){
case 0:
v1[0]=v0a-trans/4;
v1[1]=v0b+(trans+2)/4;
v1[2]=v0c+trans/2;
v1[3]=DOGPATTERN0[(trans+2)%4];
return;
case 3:
v1[0]=v0a+(trans+1)/2;
v1[1]=v0b+(trans+1)/2;
v1[2]=v0c;
v1[3]=DOGPATTERN3[(trans+1)%4];
return;
case 6:
v1[0]=v0a+(trans+3)/4;
v1[1]=v0b-(trans+1)/4;
v1[2]=v0c-(trans+1)/2;
v1[3]=DOGPATTERN6[(trans+2)%4];
return;
case 9:
v1[0]=v0a-trans/2;
v1[1]=v0b-trans/2;
v1[2]=v0c;
v1[3]=DOGPATTERN9[(trans+1)%4];
return;
//INVALID DIRECTION
default:
return;}
//++++++++++++++++
//INVALID VERTEX INDEX(?)
default:
return;}}
public static final KPoint getVertex_Transitionswise(KPoint v0,int dir,int transitions){
int[] a=new int[4];
getVertex_Transitionswise(v0.getAnt(),v0.getBat(),v0.getCat(),v0.getDog(),dir,transitions,a);
return new KPoint(a);}
/*
* ################################
* CONVERT 2D COORDINATES TO GRID COORDINATES FOR STANDARD GRID
* Given a point, get the closest vertex within the specified margin
* It chops the space up into boxes and delivers us the closest point, excluding a small degenerate space.
* It's fast.
* we're working with a standard grid here: foreward=0, twist=clockwise, fish=1.0
* If we're too far from any vertices then null is returned
* ################################
*/
private static final double
GRIDCELLBOXWIDTH=Math.sqrt(3.0),
GRIDCELLBOXHEIGHT=3.0;
public static final KPoint getStandardVertex(double[] p,double margin){
return getStandardVertex(p[0],p[1],margin);}
public static final KPoint getStandardVertex(double px,double py,double margin){
//get the box coordinates
int
bx=(int)Math.floor(px/GRIDCELLBOXWIDTH),
by=(int)Math.floor(py/GRIDCELLBOXHEIGHT);
//get the intra-box coordinates
int
ibx=(int)((px-(bx*GRIDCELLBOXWIDTH))/(GRIDCELLBOXWIDTH/4)),
iby=(int)((py-(by*GRIDCELLBOXHEIGHT))/(GRIDCELLBOXHEIGHT/12));
//we have 2 kinds of boxes
//get the actual vertex coordinates
int ka,kb,kc,kd;
//GET COORDINATES FOR BOX TYPE A
SEEK:if(Math.abs(bx%2)==Math.abs(by%2)){
//get the key v12 vertex coors
ka=(bx-by)/2;//beware those rounding integers. bx/2 - by/2 is not what we want
kc=by;
kb=ka+kc;
//analyze position within box grid : (ibx,iby)
if(ibx==0){//0 (see notes)
if(iby==0||iby==1){
kd=0;
break SEEK;
}else if(iby==6||iby==7||iby==8||iby==9){//4
kd=2;
break SEEK;
}else if(iby==10||iby==11){//5
ka=ka-1;
kc=kc+1;
kd=5;
break SEEK;
}else{//ambiguous
return null;}
}else if(ibx==1||ibx==2){
if(iby==4||iby==5||iby==6||iby==7){//3
kd=3;
break SEEK;
}else{//ambiguous
return null;}
}else{//ibx==3
if(iby==0||iby==1){//1
kd=5;
break SEEK;
}else if(iby==2||iby==3||iby==4||iby==5){//2
kd=4;
break SEEK;
}else if(iby==10||iby==11){//6
kb=kb+1;
kc=kc+1;
kd=0;
break SEEK;
}else{//ambiguous
return null;}}
//GET COORDINATES FOR BOX TYPE B
}else{
//get the key v12 vertex coors
ka=(bx-by+1)/2;
kc=by;
kb=ka+kc;
//analyze position within box grid : (ibx,iby)
if(ibx==0){
if(iby==0||iby==1){//1
ka=ka-1;
kb=kb-1;
kd=5;
break SEEK;
}else if(iby==2||iby==3||iby==4||iby==5){//2
ka=ka-1;
kb=kb-1;
kd=4;
break SEEK;
}else if(iby==10||iby==11){//6
ka=ka-1;
kc=kc+1;
kd=0;
break SEEK;
}else{//ambiguous
return null;}
}else if(ibx==1||ibx==2){
if(iby==4||iby==5||iby==6||iby==7){//3
kd=1;
break SEEK;
}else{//ambiguous
return null;}
}else{//ibx==3
if(iby==0||iby==1){//0
kd=0;
break SEEK;
}else if(iby==6||iby==7||iby==8||iby==9){//4
kd=2;
break SEEK;
}else if(iby==10||iby==11){//5
ka=ka-1;
kc=kc+1;
kd=5;
break SEEK;
}else{//ambiguous
return null;}}}
//now we have our most likely suspect
//are we close enough?
KPoint v=new KPoint(ka,kb,kc,kd);
double[] precisepoint=v.getBasicPointCoor();
if(Math.abs(px-precisepoint[0])<margin&&Math.abs(py-precisepoint[1])<margin){
return v;
}else{
return null;}}
/*
* ################################
* ANGLES
* ################################
*/
/**
* given 3 different vertices, v0,v1,v2
* return the angle formed on the right
*
* v2 o
* |
* |
* |
* v1 o <--this angle
* \
* \
* v0 o
*
*/
public static final int getRightAngle(KPoint v0,KPoint v1,KPoint v2){
int
d0=getDirection_VertexVertex(v0,v1),
d1=getDirection_VertexVertex(v1,v2);
int d=getDirectionDelta(d0,d1);
return 6-d;}
/**
* given 3 different vertices, v0,v1,v2
* return the angle formed on the left
*
* o v2
* |
* |
* |
* this angle--> o v1
* /
* /
* o v0
*
*/
public static final int getLeftAngle(KPoint v0,KPoint v1,KPoint v2){
int
d0=getDirection_VertexVertex(v0,v1),
d1=getDirection_VertexVertex(v1,v2);
int d=getDirectionDelta(d0,d1);
return 6+d;}
/**
* Get the counterclockwise offset of d1 relative to d0
* We assume that d0 and d1 have been normalized to range {0,11}
*
* o---------> d1
* | .
* | .
* | . offset angle
* |.
* |
* V
* d0
*
* @param d0 a direction
* @param d1 another direction
* @return the counterclockwise offset from d0 to d1
*/
// public static final int getCCWOffset(int d0,int d1){
// d0%=12;
// d1%=12;
// d0+=12;
// d1+=12;
// if(d1>d0)return 12-(d1-d0);
// return d0-d1;}
/*
* returns true is direction d is "between right" of the directions d0 and d1
* TODO TEST
*
* ^ d1
* |
* |
* |
* o ------> right
* |
* |
* |
* V d0
*/
public static final boolean isBetweenRight(int d0,int d1,int d){
int
d0cw=getCWOffset(d,d0),
d1ccw=getCCWOffset(d,d1);
return (d0cw+d1ccw)<11;}
/*
* returns true is direction d is "between right" of the directions d0 and d1
* TODO TEST
*
* ^ d1
* |
* |
* left |
* <------ o
* |
* |
* |
* V d0
*/
public static final boolean isBetweenLeft(int d0,int d1,int d){
int
d0ccw=getCCWOffset(d,d0),
d1cw=getCWOffset(d,d1);
return (d0ccw+d1cw)<11;}
/*
*
* returns the clockwise offset of direction d1 relative to direction d0
* ex0 : the clockwise offset of 6 relative to 2 is 4
* ex1 : the clockwise offset of 0 relative to 4 is 8
*
*
* d0
* ^
* | . .
* | . + clockwise offset
* | .
* | V
* o-----------> d1
*
*/
public static final int getCWOffset(int d0,int d1){
if(d1>=d0)
return d1-d0;
else
return 12-d0+d1;}
public static final int getCCWOffset(int d0,int d1){
int f=12-getCWOffset(d0,d1);
if(f==12)f=0;
return f;}
//TEST
public static final void main(String[] a){
Random r=new Random();
int a0,a1,cwoff;
for(int i=0;i<10;i++){
a0=r.nextInt(12);
a1=r.nextInt(12);
cwoff=getCCWOffset(a0,a1);
System.out.println("a0="+a0+" : a1="+a1+" : cwoff="+cwoff);
}}
/*
* ################################
* METAGON ANCHOR CONGRUENT POLYGON PERMUTATIONS
* Given a metagon and an anchor, we can derive a polygon
* however, implicit are 0..n other anchors that would also deliver the same polygon geometry
* The specific point location and index+ traversal direction may vary, but the same basic polygon will result.
* for example :
*
* These 3 polygons are congruent, yet they do the points differently
*
* 0 1 1 0 3 2
* o--------o o--------o o--------o
* | | | | | |
* | | | | | |
* | | | | | |
* | | | | | |
* o--------o o--------o o--------o
* 3 2 2 3 0 1
*
* Some metagon anchor systems will have several permutations, some will have just 1
* ################################
*/
/*
* Given a metagon and an anchor, producing polygon P.
* return a list of all anchors that, with this metagon, also describe polygons congruent to P.
* This list includes the original parameter anchor.
* These anchors are alternatives to the specified anchor.
* Other ways to generate the same basic polygon but with different orientation and twist.
*
* Create a polygon from params metagon and anchor : porg
* Get every pair of adjacent vertices in the polygon : va,vb
* Create 4 anchors from each of those pairs.
* That is, the vertices in foreward and reverse order, with positive and negative twist.
* ie : va,vb,pos; va,vb,neg; vb,va,pos; vb,va,neg
*
* now we have a list of prospective anchors : pa
* for every anchor in pa, create a polygon : pp
* if pp is valid, and congruent to porg, then it passes the test. Add that anchor to the list
*/
public static final List<KAnchor> getMetagonAnchorOptions(KMetagon metagon,KAnchor anchor){
KPolygon sample=metagon.getPolygon(anchor),test;
List<KAnchor> prospects=getProspectiveAnchorsForMAA(sample);
List<KAnchor> validprospects=new ArrayList<KAnchor>();
for(KAnchor a:prospects){
test=metagon.getPolygon(a);
if(test!=null&&test.isCongruent(sample))
validprospects.add(a);}
System.out.println("VALID PROSPECTS COUNT : "+validprospects.size());
return validprospects;}
private static final List<KAnchor> getProspectiveAnchorsForMAA(KPolygon p){
List<KAnchor> anchors=new ArrayList<KAnchor>();
int i0,i1,s=p.size();
KPoint v0,v1;
for(i0=0;i0<s;i0++){
i1=i0+1;
if(i1==s)i1=0;
v0=p.get(i0);
v1=p.get(i1);
anchors.add(new KAnchor(v0,v1,true));
anchors.add(new KAnchor(v0,v1,false));
anchors.add(new KAnchor(v1,v0,true));
anchors.add(new KAnchor(v1,v0,false));}
return anchors;}
}
| johnalexandergreene/Geom_Kisrhombille | GK.java |
904 | import java.util.Map;
import fi.iki.elonen.*;
import java.sql.*;
import java.io.IOException;
public class UI extends NanoHTTPD
{
public static int webPort = 8080;
public static String gpVersion = "AO";
public static String sessions = "";
public static String configFile = "";
public static void main(String[] args)
{
for (int i = 0; i < args.length; ++i)
{
if (i == 0)
webPort = Integer.parseInt(args[0]);
if (i == 1)
sessions = args[1];
if (i == 2)
configFile = args[2];
}
gpVersion = UIModel.getVersion();
ServerRunnerUI.run(UI.class);
}
public UI()
{
super(webPort);
}
@Override
public Response serve(String uri, Method method, Map<String, String> header, Map<String, String> parms, Map<String, String> files)
{
String username = parms.get("username");
String password = parms.get("password");
String submit = parms.get("submit_form");
String action_type = parms.get("action_type");
String loginMessage = "";
boolean alive = false;
String msg = "";
boolean auth = false;
if (submit == null || submit.equals(""))
submit = "0";
if (username == null)
username = "";
if (password == null)
password = "";
if (action_type == null)
action_type = "";
String sessionID = UIModel.getSessionID(header);
if (sessionID == null)
sessionID = "0";
if (action_type.equals("logout"))
{
sessionID = "0";
}
if (!uri.equals("/favicon.ico"))
{
if (submit.equals("1") && (!username.equals("")) && (!password.equals("")))
{
try
{
auth = UIModel.authenticate(username, password);
}
catch (SQLException ex)
{
loginMessage = ex.getMessage();
}
if (auth)
{
sessionID = UIModel.setSessionID(header);
try
{
UIModel.insertSession(sessionID);
}
catch (SQLException ex)
{
loginMessage = ex.getMessage();
}
}
else if (loginMessage.equals(""))
{
loginMessage = "Failed to login. Must use a valid Greenplum database account that is a SuperUser.";
}
}
if (!(sessionID.equals("0")))
{
try
{
alive = UIModel.keepAlive(sessionID);
}
catch (SQLException ex)
{
loginMessage = ex.getMessage();
}
}
if (alive)
msg = OutsourcerControl.buildPage(uri, parms);
else
sessionID = "0";
if (sessionID.equals("0"))
{
msg = UIView.viewLogin(loginMessage);
}
}
NanoHTTPD.Response out = new NanoHTTPD.Response(msg);
if (!uri.equals("/favicon.ico"))
{
out.addHeader("Set-Cookie", "OutsourcerSessionID=" + sessionID + ";");
UIModel.logger(uri, sessionID);
}
return out;
}
}
| RunningJon/outsourcer | UI.java |
905 | /* Copyright (C) <2013> University of Massachusetts Amherst
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
*
* @author Ismet Zeki Yalniz
*/
import java.util.ArrayList;
public class LCS {
// precondition: anchor words in t1 and t2 are sorted based on their term positions in respective texts.
// returns indices of elements in both sequences (in a 2D matrix) that are in the longest common subsequence
public static int[] findLCS(ArrayList<IndexEntry> t1, ArrayList<IndexEntry> t2){
int M = t1.size();
int N = t2.size();
//ArrayList<IndexEntry> LCSterms = new ArrayList<IndexEntry>();
// opt[i][j] = length of LCS of x[i..M] and y[j..N]
int[][] opt = new int[M+1][N+1];
// compute length of LCS and all subproblems via dynamic programming
for (int i = M-1; i >= 0; i--) {
String term1 = t1.get(i).getTerm();
for (int j = N-1; j >= 0; j--) {
if ( term1.equals(t2.get(j).getTerm()) ) {
opt[i][j] = opt[i+1][j+1] + 1;
}
else {
opt[i][j] = Math.max(opt[i+1][j], opt[i][j+1]);
}
}
}
int LCSindices [] = new int[2 * opt[0][0]] ;
// recover LCS itself and print it
int i = 0, j = 0, count = 0;
while(i < M && j < N) {
if (t1.get(i).getTerm().equals(t2.get(j).getTerm())) {
LCSindices[count] = i;
LCSindices[opt[0][0]+ count] = j;
i++;
j++;
count++;
}
else if (opt[i+1][j] >= opt[i][j+1]) {
i++;
}
else {
j++;
}
}
return LCSindices;
}
// Space efficient version using binary recursion but it only reports the LCS length.
// This function is not called by the recursive alignment tool.
// This is just to show how binary recursion is implemented.
public static int findLCS_3(ArrayList<IndexEntry> t1, ArrayList<IndexEntry> t2){
int M = t1.size();
int N = t2.size();
//ArrayList<IndexEntry> LCSterms = new ArrayList<IndexEntry>();
int X[] = new int[N+1];
int Y[] = new int[N+1];
// compute length of LCS and all subproblems via dynamic programming
for (int i = M-1; i >= 0; i--) {
for (int j = N-1; j >= 0; j--) {
if ( t1.get(i).getTerm().equals(t2.get(j).getTerm()) ) {
X[j] = 1 + Y[j+1];
}
else {
X[j] = Math.max(Y[j], X[j+1]);
}
}
Y = X;
}
return X[0];
}
}
| Early-Modern-OCR/RETAS | LCS.java |
906 | import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.Random;
import java.util.Scanner;
/**
* Test
*
* @author APCSA2014-15
* @version 2015-03-06
*/
public class Zoo
{
public static void main(String[] args) throws InterruptedException
{
List<Animal> animals = new ArrayList<Animal>();
System.out.println("Welcome to the Zoo!\n");
System.out.print("Building the cages");
delayDots();
System.out.print("Populating the animals");
populateAnimals(animals);
delayDots();
System.out.print("Hiring zookeepers");
delayDots();
Scanner in = new Scanner(System.in);
System.out.println("\nYou are standing in a wondrous zoo. What would you like to do?");
System.out.println("Type help to find out what you can do.\n");
String text = in.nextLine();
String msg = "";
while(!text.equals("leave"))
{
switch(text)
{
case "help" : msg = "So far we can only leave and ask for help.";
break;
default : msg = "You flail helplessly with indecision.";
}
System.out.println("\n" + msg);
System.out.println("\nYou are standing in a wondrous zoo. What would you like to do?\n");
text = in.nextLine();
}
System.out.println(Math.random() < .8 ? "\nHave a nice day! Hope you come back!" : "\nAn escaped lion eats you on your way out. Sorry!");
}
/**
* This prints an ellipses with 1 second between each period
* It then moves to the next line.
*/
public static void delayDots(int dotAmount) throws InterruptedException
{
for (int i=0; i<dotAmount; i++) {
TimeUnit.SECONDS.sleep(1);
System.out.print(".");
}
System.out.println();
}
/**
* This prints an ellipses with 1 second between each period
* It then moves to the next line.
*/
public static void delayDots() throws InterruptedException
{
delayDots(3);
}
/**
* This is where we will all collaborate.
* Construct your animal and add it to the List
* @param animals the list containing all the zoo animals
*/
public static void populateAnimals(List<Animal> animals)
{
Bear bear1 = new Bear("Care", "There's a weird symbol on his stomach and rainbows shooting from it. That can't be healthy.", "A fluffy cloud.");
Bear bear2 = new CircusBear("Fez", "This bear wears a fez and looks somewhat forlorn.", "colorful beach ball");
Frog frog1 = new Frog();
Frog frog2 = new PrinceFrog();
animals.add(bear1);
animals.add(bear2);
animals.add(frog1);
animals.add(frog2);
Shark shark1 = new Shark("Jaws", "All you see are rows upon rows of teeth.");
Blobfish blobfish1 = new Blobfish("Blobert", "The blobfish seems innocent, but beware.");
FlyingBlobfish blobfish2 = new FlyingBlobfish("Bloberto", "The blobfish seems innocent, but beware.");
animals.add(bear1);
animals.add(blobfish1);
animals.add(blobfish2);
animals.add(bear2);
animals.add(shark1);
//Tiger tiger1 = new Tiger("Bob Smith", "This tiger loves to eat and sleep.");
//animals.add(tiger1);
//Deer deer1 = new Deer("Lily", "This is a cute cute deer.");
//Deer deer2 = new Bambi("Bambi", "Hi! This is Bambi!");
//animals.add(deer1);
//animals.add(deer2);
Fox fox1 = new Fox("Red: 255 Green: 255 Blue: 255","Al Capone");
animals.add(fox1);
Duck duck1 = new Duck("Wow, that duck has 17 inch arms. He is a swole duck.", "Barbara Streisand");
Duck ducktator = new Duck("The duck seems to be leading all the other ducks in unison to mine the rocks.....", "Ducktator Kim Duck Un");
animals.add(ducktator);
animals.add(duck1);
Dragon dragon1 = new Dragon("Swag Master", "Very unpleasant attitude, he refuses to cooperate with any authority.");
Dragon dragon2 = new Dragon("Wisdom", "Having lived for centuries, this old, white-bearded dragon speak with more authority than the zoo director himself.");
animals.add(dragon1);
animals.add(dragon2);
Sloth sloth1 = new Sloth("He's definitely not the king of the jungle","Jorge Pip");
Sloth sloth2 = new AstroSloth("The best sloth astronaut you've ever seen, because he's the only one"
, "Buzz Slothstrong");
animals.add(sloth1);
animals.add(sloth2);
SCP173 scp173 = new SCP173(" SCP-173 is constructed from concrete and rebar with traces of Krylon brand spray paint." +
"/n SCP-173 is animate and extremely hostile, though the object cannot move" +
"/nwhile within a direct line of sight.", "Euclid");
animals.add(scp173);
}
}
| SPHS-CS/JavaZoo | Zoo.java |
908 | /*
* Copyright (c) 2011 Bart Massey
* [This program is licensed under the "MIT License"]
* Please see the file COPYING in the source
* distribution of this software for license terms.
*/
import java.lang.*;
import java.util.*;
/** Abstract AI for each bug in the swarm. Subclass this to
* get your own AI. */
abstract public class AI {
/** Simulation timestep in seconds, taken from
* {@link Playfield#DT} for convenience. */
double dt = Playfield.DT;
/** The controller takes in sensor data from the environment
* for processing by the AI.
*
* @param me View of my own state.
* @param agents Array of views of each other agent's state.
* @param things Array of views of state of each thing
* in the environment.
*/
abstract public void
control(MeView me, AgentView[] agents, ThingView[] things);
/** This is just a convenience routine for subtracting
* two angles. It has the desirable property that the
* difference will always be an angle ≤ π
* radians: this will enable turning toward a target
* angle in a sane way.
*
* @param target Angle to turn toward.
* @param current Current facing angle.
* @return Angular change needed to achieve desired facing.
*/
public static double angleDiff(double target, double current) {
if (Math.abs(target - current) > Math.PI)
return 2.0 * Math.PI - (current - target);
return target - current;
}
}
| BartMassey/swarm-demo | AI.java |
909 | import java.util.Scanner;
import java.text.DecimalFormat;
/**
* Calculate Pi
* @date 19 August 2014
* @author Nefari0uss
*
* This program will request the approximate number of calculations to run in calculating π.
* The final result will be displayed on the console. Assumption is that the user inputs an int.
*
*
* Uses the Gottfried Leibniz formula for calculation of π:
*
* 1 - 1/3 + 1/5 - 1/7 + 1/9 - ... = π/4
*
* Source: Wikipedia - Leibniz formula for π
**/
public class Pi {
public static void main(String[] args) {
int n = getInput();
double piValue = calculatePi(n);
printResult(piValue);
}
private static double calculatePi(double n) {
double pi = 0;
for (int i = 1; i < n; i++) {
pi += Math.pow(-1,i+1) / (2*i - 1);
}
return 4 * pi;
}
private static int getInput() {
int n = 0;
Scanner input = new Scanner(System.in);
System.out.println("How many calculations should be run for the approximation?");
try {
n = Integer.parseInt(input.nextLine());
} /** Handle input greater than Java's MAX_INT. **/
catch (NumberFormatException e) {
System.out.println("n is too large. Setting n to be the largest possible int value.");
n = Integer.MAX_VALUE;
}
input.close();
return n;
}
private static double calculateError(double piValue) {
return Math.abs(1 - piValue / Math.PI) * 100;
}
private static void printResult(double piValue) {
DecimalFormat df = new DecimalFormat("#.##");
System.out.println("The value of pi is approximately " + piValue + ".");
System.out.println("The calculated value is off by approximately " + df.format(calculateError(piValue)) + "%.");
}
}
| Nefari0uss/calculate-pi | Pi.java |