file_id
int64
1
250k
content
stringlengths
0
562k
repo
stringlengths
6
115
path
stringlengths
1
147
1
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.cips.wifilocalizationdemo; public final class R { public static final class attr { } public static final class dimen { /** Default screen margins, per the Android Design guidelines. Customize dimensions originally defined in res/values/dimens.xml (such as screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here. */ public static final int activity_horizontal_margin=0x7f040000; public static final int activity_vertical_margin=0x7f040001; } public static final class drawable { public static final int ic_launcher=0x7f020000; public static final int map_always_here_pressed=0x7f020001; public static final int plan_map=0x7f020002; } public static final class id { public static final int RelativeLayout1=0x7f080000; public static final int action_settings=0x7f080006; public static final int frameLayout_1=0x7f080001; public static final int imageButton1=0x7f080003; public static final int imageView1=0x7f080002; public static final int textView_Status=0x7f080005; public static final int textView_Tips=0x7f080004; } public static final class layout { public static final int activity_main=0x7f030000; } public static final class menu { public static final int main=0x7f070000; } public static final class string { public static final int action_settings=0x7f050001; public static final int app_name=0x7f050000; public static final int hello_world=0x7f050002; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f060000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f060001; } }
jiangqideng/WiFiLocalizationDemo
R.java
2
/*--- 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 ISwitchR interface to be used as to switch methods to return reference instance. @see ISwitchR @author Satoru Sugihara */ public class Ir implements ISwitchR{ public static final Ir i=new Ir(); }
sghr/iGeo
Ir.java
3
import java.util.*; class Fathe { public void call() { System.out.println("Call"); } } class Chill extends Fathe { public void debit() { System.out.println("debit"); } } class Ot { public static void main(String s[]) { Fathe f=new Chill(); f.call();//gets successfully called as obvious f.debit();//wont get called (compilation error)because we cant call method of class using // the ref variable of another class.f is a reference variable of Fathe class but contains reference vaiable of // Chill class. } }
asad9711/Key-Points-in-Java
Ot.java
4
//******************************************************* // C.java // the class reprsents C // Author: liron mizrahi //******************************************************* public class C { public void foo(D d) { System.out.println("cd"); } }// end of class C
lironmiz/Computer-Science-in-Java
C.java
5
package StudentInformationSystem; import java.awt.Color; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.DefaultCellEditor; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.event.CellEditorListener; import javax.swing.table.DefaultTableModel; import java.awt.Font; import javax.swing.UIManager; import com.github.lgooddatepicker.components.DatePicker; public class StudentInformationSystem { private JFrame frame; private JTextField sID; private JTextField fName; private JTextField mName; private JTextField lName; private JTextField Age; private JTextField mother; private JTextField father; private JTextField cp; private JTextField address; private JTable table_2; private static Connection con = null; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { // Class.forName("org.sqlite.JDBC"); // con = DriverManager.getConnection("jdbc:sqlite:C:\\\\Users\\\\Von\\\\Desktop\\\\sql.db"); //con.setAutoCommit(false); StudentInformationSystem window = new StudentInformationSystem(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public StudentInformationSystem() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { JComboBox bading = new JComboBox(); bading.setForeground(new Color(240, 128, 128)); bading.setBackground(new Color(255, 228, 225)); frame = new JFrame(); frame.setResizable(false); frame.getContentPane().setBackground(new Color(255, 204, 204)); frame.getContentPane().setForeground(new Color(204, 153, 51)); frame.setBounds(100, 100, 1014, 406); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); DefaultTableModel model = new DefaultTableModel(); JLabel lblNewLabel = new JLabel("First Name : "); lblNewLabel.setBounds(20, 44, 86, 14); frame.getContentPane().add(lblNewLabel); //StudentID, FirstName, MiddleName, LastName, Birthdate, Age, Gender, MothersnName, FathersName, CellphoneNumber, Address model.addColumn(""); model.addColumn("Student ID"); model.addColumn("Name"); model.addColumn("Gender"); model.addColumn("Age"); model.addColumn("Birthday"); model.addColumn("Mother"); model.addColumn("Father"); model.addColumn("Cell No."); model.addColumn("Address"); table_2 = new JTable(model); table_2.setForeground(new Color(255, 182, 193)); table_2.setBackground(new Color(240, 128, 128)); table_2.getColumnModel().getColumn(0).setPreferredWidth(23); table_2.getColumn("").setCellRenderer(new JCheckRender()); table_2.getColumn("").setCellEditor(new JCheckBoxEditor()); JLabel lblNewLabel_1 = new JLabel("Middle Name :"); lblNewLabel_1.setBounds(20, 69, 103, 14); frame.getContentPane().add(lblNewLabel_1); JLabel lblNewLabel_2 = new JLabel("Last Name : "); lblNewLabel_2.setBounds(20, 90, 86, 14); frame.getContentPane().add(lblNewLabel_2); JLabel lblNewLabel_3 = new JLabel("Birthdate :"); lblNewLabel_3.setBounds(20, 115, 86, 14); frame.getContentPane().add(lblNewLabel_3); JLabel lblNewLabel_4 = new JLabel("Age : "); lblNewLabel_4.setBounds(20, 140, 59, 14); frame.getContentPane().add(lblNewLabel_4); JLabel lblNewLabel_5 = new JLabel("Gender :"); lblNewLabel_5.setBounds(20, 163, 59, 14); frame.getContentPane().add(lblNewLabel_5); JLabel lblNewLabel_6 = new JLabel("Mother's Name :"); lblNewLabel_6.setBounds(20, 188, 103, 14); frame.getContentPane().add(lblNewLabel_6); JLabel lblNewLabel_7 = new JLabel("Father's Name :"); lblNewLabel_7.setBounds(20, 213, 103, 14); frame.getContentPane().add(lblNewLabel_7); JLabel lblNewLabel_8 = new JLabel("Cellphone Number : "); lblNewLabel_8.setBounds(20, 236, 127, 14); frame.getContentPane().add(lblNewLabel_8); JLabel lblNewLabel_9 = new JLabel("Student ID :"); lblNewLabel_9.setFont(UIManager.getFont("Button.font")); lblNewLabel_9.setBounds(20, 25, 86, 14); frame.getContentPane().add(lblNewLabel_9); JLabel lblNewLabel_10 = new JLabel("Address : "); lblNewLabel_10.setBounds(20, 261, 86, 14); frame.getContentPane().add(lblNewLabel_10); sID = new JTextField(); sID.setBackground(new Color(255, 228, 225)); sID.setBounds(93, 22, 201, 17); frame.getContentPane().add(sID); sID.setColumns(10); fName = new JTextField(); fName.setBackground(new Color(255, 228, 225)); fName.setBounds(93, 44, 201, 17); frame.getContentPane().add(fName); fName.setColumns(10); mName = new JTextField(); mName.setBackground(new Color(255, 228, 225)); mName.setBounds(103, 69, 191, 17); frame.getContentPane().add(mName); mName.setColumns(10); lName = new JTextField(); lName.setBackground(new Color(255, 228, 225)); lName.setBounds(103, 90, 191, 17); frame.getContentPane().add(lName); lName.setColumns(10); Age = new JTextField(); Age.setBackground(new Color(255, 228, 225)); Age.setColumns(10); Age.setBounds(62, 137, 232, 17); frame.getContentPane().add(Age); mother = new JTextField(); mother.setBackground(new Color(255, 228, 225)); mother.setColumns(10); mother.setBounds(120, 185, 174, 17); frame.getContentPane().add(mother); father = new JTextField(); father.setBackground(new Color(255, 228, 225)); father.setColumns(10); father.setBounds(120, 210, 174, 17); frame.getContentPane().add(father); cp = new JTextField(); cp.setBackground(new Color(255, 228, 225)); cp.setColumns(10); cp.setBounds(132, 233, 162, 17); frame.getContentPane().add(cp); address = new JTextField(); address.setBackground(new Color(255, 228, 225)); address.setColumns(10); address.setBounds(89, 258, 205, 17); frame.getContentPane().add(address); DatePicker Bdate = new DatePicker(); Bdate.getComponentDateTextField().setBackground(Color.PINK); Bdate.setBounds(90, 113, 204, 20); JButton btnNewButton = new JButton("ADD"); btnNewButton.setForeground(new Color(240, 128, 128)); btnNewButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { String sid=sID.getText(); String fname=fName.getText(); String mname=mName.getText(); String lname=lName.getText(); String bday=Bdate.getDateStringOrEmptyString(); String age=Age.getText(); String gender = bading.getSelectedItem().toString(); String mtname=mother.getText(); String ftname=father.getText(); String cnum=cp.getText(); String addr=address.getText(); try { PreparedStatement stmt= con.prepareStatement( "INSERT INTO Students (StudentID, FirstName, MiddleName, LastName, Birthdate, Age, Gender, MothersnName, FathersName, CellphoneNumber, Address) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); stmt.setString(1, sid); stmt.setString(2, fname); stmt.setString(3, mname); stmt.setString(4, lname); stmt.setString(5, bday); stmt.setString(6, age); stmt.setString(7, gender); stmt.setString(8, mtname); stmt.setString(9, ftname); stmt.setString(10, cnum); stmt.setString(11, addr); stmt.executeUpdate(); con.commit(); stmt.close(); String query = "Select * from Students"; PreparedStatement pst = con.prepareStatement(query); ResultSet resultset = pst.executeQuery(); while(resultset.next()) { model.addRow(new Object[] {false, resultset.getString("StudentID"), resultset.getString("FirstName")+ " " +resultset.getString("LastName"), resultset.getString("Gender"), resultset.getString("Age"), resultset.getString("Birthdate"),resultset.getString("MothersnName"),resultset.getString("FathersName"),resultset.getString("CellphoneNumber"),resultset.getString("Address")}); } }catch (Exception j) { j.printStackTrace(); } } }); btnNewButton.setBounds(426, 317, 180, 23); frame.getContentPane().add(btnNewButton); JButton btnNewButton_3 = new JButton("DELETE"); btnNewButton_3.setForeground(new Color(240, 128, 128)); btnNewButton_3.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { int cons = 0; for(int i = 0; i < table_2.getRowCount(); i++) { boolean isSel = (boolean) table_2.getValueAt(i, 0); PreparedStatement stmt = null; if(isSel) { System.out.println("Deleting a row in the table..."); String sql = "DELETE FROM Students WHERE StudentID = ?"; try { stmt = con.prepareStatement(sql); stmt.setString(1, (String) table_2.getValueAt(i, 1)); stmt.executeUpdate(); con.commit(); stmt.close(); cons++; } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } Statement as; try { as = con.createStatement(); ResultSet resultset = as.executeQuery("SELECT * FROM Students"); model.setRowCount(0); while(resultset.next()) { model.addRow(new Object[] {false, resultset.getString("StudentID"), resultset.getString("FirstName")+ " " +resultset.getString("LastName"), resultset.getString("Gender"), resultset.getString("Age"), resultset.getString("Birthdate"),resultset.getString("MothersnName"),resultset.getString("FathersName"),resultset.getString("CellphoneNumber"),resultset.getString("Address")}); } as.close(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } JOptionPane.showMessageDialog(null, cons+" item deleted successfully!"); } }); btnNewButton_3.setBounds(695, 317, 180, 23); frame.getContentPane().add(btnNewButton_3); bading.setModel(new DefaultComboBoxModel(new String[] {"Male", "Female", "Prefer not to say"})); bading.setBounds(76, 161, 218, 18); frame.getContentPane().add(bading); JScrollPane scrollPane_1 = new JScrollPane(); scrollPane_1.setBounds(304, 11, 684, 295); frame.getContentPane().add(scrollPane_1); scrollPane_1.setViewportView(table_2); frame.getContentPane().add(Bdate); } } class JCheckBoxEditor extends DefaultCellEditor { /** * */ private static final long serialVersionUID = 3846878501975009951L; public JCheckBoxEditor() { super(new JCheckBox()); } @Override public void addCellEditorListener(CellEditorListener l) { // TODO Auto-generated method stub super.addCellEditorListener(l); } }
CrLn-66/Butete
a.java
6
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode mergeKLists(ListNode[] lists) { //FBIP 3R //divide and conquer if (lists == null || lists.length == 0) return null; if (lists.length == 1) return lists[0]; int mid = (lists.length - 1) / 2; ListNode list1 = mergeKLists(Arrays.copyOfRange(lists, 0, mid + 1)); //copyOfRange does not include the last index ListNode list2 = mergeKLists(Arrays.copyOfRange(lists, mid + 1, lists.length)); return mergeTwoLists(list1, list2); } private ListNode mergeTwoLists(ListNode l1, ListNode l2){ if (l1 == null) return l2; if (l2 == null) return l1; if (l1.val < l2.val){ l1.next = mergeTwoLists(l1.next, l2); return l1; } else { l2.next = mergeTwoLists(l1, l2.next); return l2; } } }
EdwardHXu/FBIP-LC
23.java
7
/* * Decompiled with CFR 0.152. * * Could not load the following classes: * net.minecraft.util.math.MathHelper */ import i.gishreloaded.deadcode.wrappers.Wrapper; import net.minecraft.util.math.MathHelper; public class d { public double a; public double b; public double c; public d() { this.a = 0.1; } public d(double d2) { this.a = d2; } public d(double d2, double d3) { this.a = d2; this.b = d3; this.c = d3; } public void a() { this.b = 0.0; this.c = 0.0; } public void a(boolean bl) { this.c = MathHelper.clamp((double)(this.c + (bl ? this.a : -this.a) * (double)Wrapper.INSTANCE.getMinecraft().getTickLength() * (double)1.8f), (double)0.0, (double)1.0); this.b = d.a(this.c); } public double b() { return this.b; } private static /* synthetic */ double a(double d2) { return 1.0 - Math.pow(1.0 - d2, 3.0); } }
n3xtbyte/deadcode-source
d.java
8
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import com.sun.security.auth.module.Krb5LoginModule; import java.io.*; import java.lang.reflect.Constructor; import java.net.Authenticator; import java.net.PasswordAuthentication; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.security.PrivilegedExceptionAction; import java.util.*; import javax.security.auth.Subject; import javax.security.auth.kerberos.KerberosKey; import javax.security.auth.kerberos.KerberosTicket; import javax.security.auth.login.*; import org.ietf.jgss.*; import java.util.logging.ConsoleHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; /** * Kerberos command line tool. */ public class K { private static Oid oidk; private static Oid oids; static { try { oidk = new Oid("1.2.840.113554.1.2.2"); oids = new Oid("1.3.6.1.5.5.2"); } catch (Exception e) { throw new AssertionError(e); } } private static boolean isNative = false; private static boolean isDebug = false; private static int outputStyle = 0; // 0: auto, 1:color, 2:prefix private static boolean sm = false; private static boolean verbose = false; public static void main(String[] args) throws Exception { if (args.length == 0) { System.out.println("Usage: java K <common option>* <command> <option>*\n\n" + "Common options:\n\n" + " -n[=lib] uses native provider\n" + " -d turns on debug\n"); System.out.println(q_help); System.out.println(); System.out.println(p_help); System.out.println(); System.out.println(w_help); System.out.println(); System.out.println(c_help); } else { for (int i=0; i<args.length; i++) { if (args[i].equals("-d")) { isDebug = true; System.setProperty("sun.security.nativegss.debug", "true"); System.setProperty("sun.security.spnego.debug", "true"); System.setProperty("sun.security.krb5.debug", "true"); System.setProperty("sun.security.jgss.debug", "true"); } else if (args[i].startsWith("-n")) { isNative = true; if (args[i].length() > 2) { if (args[i].charAt(2) == '=') { System.setProperty("sun.security.jgss.lib", args[i].substring(3)); } else { throw new Exception("Unknown command " + args[i]); } } } else { String command = args[i]; args = Arrays.copyOfRange(args, i + 1, args.length); System.setProperty("sun.security.jgss.native", Boolean.toString(isNative)); switch (command) { case "q": q(args); break; case "p": p(args); break; case "w": w(args); break; case "c": c(args); break; default: throw new Exception("Unknown command " + command); } return; } } } } /** * Login to a KDC. user/pass, user/keytab, -/- (default ccache), * -/keytab (unbound), user/-- (default keytab), -/-- (unbound default keytab). * @param name username * @param pt password or keytab * @param init true if is initiator * @return the subject */ private static Subject krb5login(String name, String pt, boolean init) throws LoginException { Subject subject = new Subject(); if (isNative) { System.setProperty("javax.security.auth.useSubjectCredsOnly", "false"); return subject; } Krb5LoginModule krb5 = new Krb5LoginModule(); Map<String, String> map = new HashMap<String, String>(); Map<String, Object> shared = new HashMap<String, Object>(); map.put("doNotPrompt", "true"); if (isDebug) { map.put("debug", "true"); } if (init) { map.put("isInitiator", "true"); } else { map.put("storeKey", "true"); map.put("isInitiator", "false"); } if (!name.equals("-")) { map.put("principal", name); } if (pt.equals("-")) { map.put("useTicketCache", "true"); } else if (pt.equals("--")) { if (name.equals("-")) { map.put("principal", "*"); } map.put("useKeyTab", "true"); } else if (new File(pt).exists()) { if (name.equals("-")) { map.put("principal", "*"); } map.put("useKeyTab", "true"); map.put("keyTab", pt); } else { map.put("useFirstPass", "true"); shared.put("javax.security.auth.login.name", name); shared.put("javax.security.auth.login.password", pt.toCharArray()); } krb5.initialize(subject, null, shared, map); krb5.login(); krb5.commit(); return subject; } /** * Creates a GSSName, whose type depends on the service's format. * Could be name, name@REALM, name@host. */ private static GSSName createName(GSSManager manager, String service) throws GSSException { if (service.indexOf('@') >= 0) { String second = service.substring(service.indexOf('@') + 1); if (second.toUpperCase().equals(second)) { // Just a realm return manager.createName(service, GSSName.NT_USER_NAME); } else { return manager.createName( service, GSSName.NT_HOSTBASED_SERVICE); } } else { return manager.createName(service, GSSName.NT_USER_NAME); } } static String q_help = "java K [-n] [-d] q <user> <key_or_tab> [<impersonate>] <peer> [-t] [-s] [-d] [-m]" + "\n\nGenerates an AP_REQ." + "\nFor example: java K q username password -m -t\n" + "\n user my username, '-' uses the one in ccache" + "\n key_or_tab password/keytab, '-' ccache, '--' default keytab" + "\n impersonate impersonates this guy, if provided" + "\n peer peer principal name" + "\n -talk talks to peer" + "\n -spnego uses SPNEGO, otherwise, krb5" + "\n -mutual requests mutual" + "\n -deleg requests cred deleg"; public static void q(final String[] args) throws Exception { Subject subj = krb5login(args[0], args[1], true);; Subject.doAs(subj, new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { boolean deleg = false; boolean mutual = false; boolean talk = false; boolean useSPNEGO = false; String nextAlg = args[2]; String nextNextAlg = null; String service, impersonate; for (int i=3; i<args.length; i++) { String s = args[i]; if (s.equalsIgnoreCase("-s")) { useSPNEGO = true; } else if (s.equalsIgnoreCase("-d")) { deleg = true; } else if (s.equalsIgnoreCase("-t")) { talk = true; } else if (s.equalsIgnoreCase("-m")) { mutual = true; } else { nextNextAlg = s; } } if (nextNextAlg == null) { impersonate = null; service = nextAlg; } else { impersonate = nextAlg; service = nextNextAlg; } GSSManager manager = GSSManager.getInstance(); GSSCredential cred = null;//manager.createCredential(GSSCredential.INITIATE_ONLY); if (impersonate != null) { GSSName other = manager.createName(impersonate, GSSName.NT_USER_NAME); Class c = Class.forName("com.sun.security.jgss.ExtendedGSSCredential"); cred = (GSSCredential)c.getMethod("impersonate", GSSName.class).invoke(cred, other); //cred = ((ExtendedGSSCredential)cred).impersonate(other); } GSSContext context = manager.createContext( createName(manager, service), useSPNEGO ? oids : oidk, cred, GSSContext.DEFAULT_LIFETIME); if (deleg) context.requestCredDeleg(deleg); context.requestMutualAuth(mutual); byte[] token = new byte[0]; while (!context.isEstablished()) { token = context.initSecContext(token, 0, token.length); if (token != null) { writeToken("AP-REQ", token); } System.out.println("isEstablished/isProtReady: " + context.isEstablished() + "/" + context.isProtReady()); if (!context.isEstablished()) { token = readToken("AP-REP"); } } statusContext(context); if (talk) { talkOut(context, "Client to server"); talkIn(context); } context.dispose(); if (cred != null) { cred.dispose(); } if (isDebug) print(subj); return null; } }); } static String p_help = "java K [-n] [-d] p <user> <key_or_tab> [-t] [-s] [<backend> [-t] [-s] [-d] [-m]]\n" + "\nAccepts an AP_REQ and possibly creates another" + "\nFor example: java K p service keytab -t backend -t\n" + "\n user my username, '-' uses ccache" + "\n key_or_tab my password or keytab, '-' means ccache" + "\n -talk talks with client" + "\n -spnego uses SPNEGO, otherwise, krb5" + "\n backend if exists, getDeleg and creates an AP-REQ to backend" + "\n -talk talks with backend" + "\n -spnego uses SPNEGO to backend, otherwise, krb5" + "\n -mutual requests mutual to backend" + "\n -deleg requests cred deleg to backend"; public static void p(final String[] args) throws Exception { Subject subj = krb5login(args[0], args[1], false); Subject.doAs(subj, new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { String service = null; boolean deleg = false; boolean mutual = false; boolean talkToClient = false; boolean talkToBackend = false; boolean useSPNEGOToClient = false; boolean useSPNEGOToBackend = false; for (int i=2; i<args.length; i++) { String s = args[i]; if (s.equalsIgnoreCase("-s")) { if (service == null) useSPNEGOToClient = true; else useSPNEGOToBackend = true; } else if (s.equalsIgnoreCase("-d")) { deleg = true; } else if (s.equalsIgnoreCase("-t")) { if (service == null) talkToClient = true; else talkToBackend = true; } else if (s.equalsIgnoreCase("-m")) { mutual = true; } else { service = s; } } GSSManager manager = GSSManager.getInstance(); GSSContext context = manager.createContext(manager.createCredential( args[0].equals("-") ? null : createName(manager, args[0]), GSSCredential.INDEFINITE_LIFETIME, useSPNEGOToClient ? oids : oidk, GSSCredential.ACCEPT_ONLY)); while (!context.isEstablished()) { byte[] token = readToken("AP-REQ"); token = context.acceptSecContext(token, 0, token.length); if (token != null) { writeToken("AP-REP", token); } System.out.println("isEstablished/isProtReady: " + context.isEstablished() + "/" + context.isProtReady()); } statusContext(context); if (talkToClient) { talkIn(context); talkOut(context, "Server to client"); } if (service != null) { GSSName serverName = createName(manager, service); GSSCredential ded = context.getDelegCred(); System.out.println("Use delegated credentials as " + context.getSrcName()); context.dispose(); //System.out.println(ded.getRemainingInitLifetime(oid)); context = manager.createContext( serverName, useSPNEGOToBackend ? oids : oidk, ded, GSSContext.DEFAULT_LIFETIME); context.requestMutualAuth(mutual); if (deleg) { context.requestCredDeleg(true); } byte[] token = new byte[0]; while (!context.isEstablished()) { token = context.initSecContext(token, 0, token.length); if (token != null) { writeToken("AP-REQ", token); } System.out.println("isEstablished/isProtReady: " + context.isEstablished() + "/" + context.isProtReady()); if (!context.isEstablished()) { token = readToken("AP-REP"); } } statusContext(context); if (talkToBackend) { talkOut(context, "Server to backend"); talkIn(context); } context.dispose(); if (ded != null) { ded.dispose(); } } else { context.dispose(); } if (isDebug) print(subj); return null; } }); } private static void statusContext(GSSContext context) throws GSSException { System.out.println("getSrcName/getTargName: " + context.getSrcName() + " -> " + context.getTargName()); System.out.println("State: mutual" + (context.getMutualAuthState()?"+":"-") + " deleg" + (context.getCredDelegState()?"+":"-") + " anonymous" + (context.getAnonymityState()?"+":"-") + " conf" + (context.getConfState()?"+":"-") + " integ" + (context.getIntegState()?"+":"-") + " replay" + (context.getReplayDetState()?"+":"-") + " sequence" + (context.getSequenceDetState()?"+":"-")); } private static void talkOut(GSSContext context, String msg) throws Exception { byte[] data = msg.getBytes(); byte[] data2 = data; MessageProp prop = new MessageProp(true); writeToken("wrap", context.wrap(data, 0, data.length, prop)); writeToken("wrap", context.wrap(data2, 0, data2.length, prop)); writeToken("wrap", context.wrap(data, 0, data.length, prop)); writeToken("wrap", context.wrap(data2, 0, data2.length, prop)); } private static void showProp(String label, MessageProp prop) { System.out.println(label + " priv" + (prop.getPrivacy()?"+":"-") + " dup" + (prop.isDuplicateToken()?"+":"-") + " gap" + (prop.isGapToken()?"+":"-") + " old" + (prop.isOldToken()?"+":"-") + " unseq" + (prop.isUnseqToken()?"+":"-")); // Wait until 8201627 is resolved. if (prop.isDuplicateToken() || prop.isGapToken() || prop.isOldToken() || prop.isUnseqToken()) { throw new RuntimeException("Bad prop"); } } private static void talkIn(GSSContext context) throws Exception { MessageProp prop; byte[] token1 = readToken("wrap"); byte[] token2 = readToken("wrap"); byte[] token3 = readToken("wrap"); byte[] token4 = readToken("wrap"); prop = new MessageProp(true); byte[] msg = context.unwrap(token1, 0, token1.length, prop); showProp("unwrap: \"" + new String(msg) + "\"", prop); prop = new MessageProp(true); byte[] msg2 = context.unwrap(token2, 0, token2.length, prop); showProp("unwrap: \"" + new String(msg2) + "\"", prop); prop = new MessageProp(true); byte[] msg3 = context.unwrap(token3, 0, token3.length, prop); showProp("unwrap: \"" + new String(msg) + "\"", prop); prop = new MessageProp(true); byte[] msg4 = context.unwrap(token4, 0, token4.length, prop); showProp("unwrap: \"" + new String(msg2) + "\"", prop); } static void writeToken(String name, byte[] token) throws Exception { String start = "-----START " + name + "-----"; String end = "-----END " + name + "-----"; System.out.println(start); System.out.println(Base64.getEncoder().encodeToString(token)); System.out.println(end); } static byte[] readToken(String name) throws Exception { String start = "-----START " + name + "-----"; String end = "-----END " + name + "-----"; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); boolean in = false; System.out.println(">>> Waiting for " + name + "..."); while (true) { String line = br.readLine(); if (line == null) throw new Exception("No token to read"); if (line.equals(start)) { in = true; } else if (in) { if (line.equals(end)) { return Base64.getDecoder().decode(sb.toString()); } else { sb.append(line); } } } } private static void print(Subject s) { System.out.println(s.getPrincipals()); for (Object o: s.getPrivateCredentials()) { if (o instanceof KerberosTicket) { KerberosTicket kt = (KerberosTicket)o; System.out.println("KerberosTicket: " + kt.getClient() + " -> " + kt.getServer()); } else if (o instanceof KerberosKey) { KerberosKey kk = (KerberosKey)o; System.out.println("KerberosKey: " + kk); } else { System.out.println(o.getClass()); } } } /////////////////////////////////////////////////////////////////// static String w_help = "java K [-n] [-d] w [user] [pass] [scheme] <url>*" + "\n\nGrab a URL" + "\nFor example: java K w - - kerberos http://www.protected.com\n" + "\n user my username" + "\n pass my password" + "\n scheme Negotiate or Kerberos or NTLM etc" + "\n url URL"; public static void w(String[] args) throws Exception { String HTTPLOG = "sun.net.www.protocol.http.HttpURLConnection"; Logger.getLogger(HTTPLOG).setLevel(Level.ALL); Handler h = new ConsoleHandler(); h.setLevel(Level.ALL); Logger.getLogger(HTTPLOG).addHandler(h); System.setProperty("http.maxRedirects", "10"); String userName = null; String password = null; for (String arg : args) { if (arg.startsWith("http")) { System.err.println("\u001b[1;37;41m" + arg); System.err.println("\u001b[m\n"); URL url = new URL(arg); InputStream ins = url.openConnection().getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(ins)); String str; int pos = 0; while ((str = reader.readLine()) != null) { if (pos++ > 10) { System.out.print("."); } else { System.out.println(str); } } System.out.println(); } else if (arg.equalsIgnoreCase("negotiate") || arg.equalsIgnoreCase("kerberos")) { System.setProperty("http.auth.preference", arg); } else if (userName == null) { userName = arg; } else if (password == null) { password = arg; Authenticator.setDefault( new MyAuthenticator(userName, password.toCharArray())); userName = null; password = null; } else { throw new Exception("what is " + arg); } } } static class MyAuthenticator extends Authenticator { String user; char[] pass; public MyAuthenticator (String user, char[] pass) { this.user = user; this.pass = pass; } public PasswordAuthentication getPasswordAuthentication () { System.err.println("::::: PROVIDING " + getRequestingScheme() + " PASSWORD AND USERNAME"); return new PasswordAuthentication (user, pass); } } /////////////////////////////////////////////////////////////////// static String c_help = "java K c <option>* <command>+" + "\n\nChoreograph several commands talking to each other" + "\nFor example: java K c \"K -n q - - server -d\" \"K p server keytab backend\" -d 3000 \"K p backend keytab\"\n" + "\n -c always uses color output" + "\n -p always uses prefix output" + "\n -j <java> uses this executable" + "\n -d <delay> delay in milliseconds" + "\n -s Run with security manager" + "\n -v Display full data" + "\n command Arguments of a java command"; public static void c(String[] args) throws Exception { String java = System.getProperty("java.home") + "/bin/java"; Files.write(Paths.get("policy"), Arrays.asList( "grant {", " permission java.security.AllPermission;", "};" )); for (int i = 0; i < args.length; i++) { String arg = args[i]; switch (arg) { case "-c": outputStyle = 1; break; case "-p": outputStyle = 2; break; case "-s": sm = true; break; case "-j": java = args[++i]; break; case "-d": Thread.sleep(Long.parseLong(args[++i])); break; case "-v": verbose = true; break; default: run(java, arg); } } } static String inheritProperty(String k) { String v = System.getProperty(k); return v == null ? "" : (" -D" + k + "=" + v + " "); } static void run(String java, String s) throws Exception { if (sm) { s = "-Djava.security.manager -Djava.security.policy=policy " + s; } new Runner(java + " " + inheritProperty("java.class.path") + inheritProperty("java.security.krb5.conf") + inheritProperty("sun.security.jgss.lib") + inheritProperty("sun.security.krb5.acceptor.sequence.number.nonmutual") + " -ea -esa " + s); } static class Runner { Process p; Printer pt; Runner(String cmd) throws Exception { p = new ProcessBuilder(cmd.split(" +")).start(); pt = Printer.get(); new ReadThread(this).start(); new ErrThread(this).start(); } } static class ReadThread extends Thread { Runner r; static String WAIT_HEAD = ">>> Waiting for "; static String DATA_START = "-----START "; static String DATA_END = "-----END "; ReadThread(Runner r) { this.r = r; } @Override public void run() { BufferedReader br = new BufferedReader( new InputStreamReader(r.p.getInputStream())); try { String block = null; String label = null; while (true) { String s = br.readLine(); if (s == null) break; r.pt.p(s.length() > 100 && !verbose ? (s.substring(0, 100) + "...") : s); if (s.startsWith(WAIT_HEAD)) { String name = s.substring(WAIT_HEAD.length(), s.length() - 3); String data = Data.dataFor(name, r); if (data != null) { r.pt.p3(">>> See " + name); r.p.getOutputStream().write(data.getBytes()); r.p.getOutputStream().flush(); } else { Data.setRunner(name, r); } } else if (s.startsWith(DATA_START)) { label = s.substring(DATA_START.length(), s.length() - 5); block = s + "\n"; } else if (s.startsWith(DATA_END)) { block += s + "\n"; Runner r2 = Data.runnerFor(label, r); if (r2 != null) { r2.pt.p3(">>> See " + label); r2.p.getOutputStream().write(block.getBytes()); r2.p.getOutputStream().flush(); } else { Data.setData(label, block, r); } label = null; } else if (label != null) { block += s + "\n"; } } } catch (IOException ioe) { ioe.printStackTrace(); } } } static class ErrThread extends Thread { Runner r; ErrThread(Runner r) { this.r = r; } @Override public void run() { BufferedReader br = new BufferedReader( new InputStreamReader(r.p.getErrorStream())); try { while (true) { String s = br.readLine(); if (s == null) break; r.pt.p4(s); } } catch (IOException ioe) { ioe.printStackTrace(); } } } static class Data { // Proc waiting for data: label, null, r // Data waiting for proc: label, data, r static LinkedList<Object[]> data = new LinkedList<>(); public synchronized static void setData(String label, String block, Runner r) { data.add(new Object[] {label, block, r}); } public synchronized static Runner runnerFor(String label, Runner me) { Iterator<Object[]> iter = data.iterator(); while (iter.hasNext()) { Object[] d = iter.next(); if (d[0].equals(label) && d[1] == null && d[2] != me) { iter.remove(); return (Runner) d[2]; } } return null; } public synchronized static void setRunner(String name, Runner r) { data.add(new Object[] {name, null, r}); } public synchronized static String dataFor(String name, Runner me) { Iterator<Object[]> iter = data.iterator(); while (iter.hasNext()) { Object[] d = iter.next(); if (d[0].equals(name) && d[1] != null && d[2] != me) { iter.remove(); return (String) d[1]; } } return null; } } static abstract class Printer { int c; int fore; static int now = 2; static Printer get() { int cc = now++; if (outputStyle == 0) { if (System.getenv("windir") != null) { return new Mono(cc); } else { return new Color(cc, cc == 7 ? 30 : 37); } } else if (outputStyle == 1) { return new Color(cc, cc == 7 ? 30 : 37); } else { return new Mono(cc); } } abstract void p(String s); abstract void p3(String s); abstract void p4(String s); static class Color extends Printer { Color(int c, int fore) { this.c = c; this.fore = fore; } void p(String s) { // color System.out.println("\u001b[1;" + fore + ";4" + c + "m" + s + "\u001b[m"); } void p3(String s) { // italic System.out.println("\u001b[1;3;" + fore + ";4" + c + "m" + s + "\u001b[m"); } void p4(String s) { // underline System.out.println("\u001b[1;4;" + fore + ";4" + c + "m" + s + "\u001b[m"); } } static class Mono extends Printer { Mono(int c) { this.c = c; } void p(String s) { // color System.out.println(c + ": " + s); } void p3(String s) { // italic System.out.println(c + "> " + s); } void p4(String s) { // underline System.out.println(c + "< " + s); } } } }
wangweij/ktest
K.java
9
/* This file does nothing but load the SBML library */ import org.sbml.libsbml.*; public class A { public Model getModel() { return new Model(0,0); } /** * The following static block is needed in order to load the * the libSBML Java module when the application starts. */ static { String varname; String shlibname; if (System.getProperty("mrj.version") != null) { varname = "DYLD_LIBRARY_PATH"; // We're on a Mac. shlibname = "libsbmlj.jnilib and/or libsbml.dylib"; } else { varname = "LD_LIBRARY_PATH"; // We're not on a Mac. shlibname = "libsbmlj.so and/or libsbml.so"; } try { System.loadLibrary("sbmlj"); Class.forName("org.sbml.libsbml.libsbml"); } catch (UnsatisfiedLinkError e) { System.err.println("Error encountered while attempting to load libSBML:"); e.printStackTrace(); System.err.println("Please check the value of your " + varname + " environment variable and/or" + " your 'java.library.path' system property" + " (depending on which one you are using) to" + " make sure it lists all the directories needed to" + " find the " + shlibname + " library file and the" + " libraries it depends upon (e.g., the XML parser)."); System.exit(1); } catch (ClassNotFoundException e) { e.printStackTrace(); System.err.println("Error: unable to load the file libsbmlj.jar." + " It is likely your -classpath option and/or" + " CLASSPATH environment variable do not" + " include the path to the file libsbmlj.jar."); System.exit(1); } catch (SecurityException e) { System.err.println("Error encountered while attempting to load libSBML:"); e.printStackTrace(); System.err.println("Could not load the libSBML library files due to a"+ " security exception.\n"); System.exit(1); } } }
bio-ontology-research-group/sbml-harvester
A.java
10
import java.io.File; import java.io.FileWriter; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; import java.util.List; import net.minecraft.server.MinecraftServer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class x extends i { private static final Logger a = ; private long b; private int c; public String c() { return "debug"; } public int a() { return 3; } public String b(m ☃) { return "commands.debug.usage"; } public void a(MinecraftServer ☃, m ☃, String[] ☃) throws bz { if (☃.length < 1) { throw new cf("commands.debug.usage", new Object[0]); } if (☃[0].equals("start")) { if (☃.length != 1) { throw new cf("commands.debug.usage", new Object[0]); } a(☃, this, "commands.debug.start", new Object[0]); ☃.aq(); this.b = MinecraftServer.av(); this.c = ☃.ap(); } else if (☃[0].equals("stop")) { if (☃.length != 1) { throw new cf("commands.debug.usage", new Object[0]); } if (!☃.c.a) { throw new bz("commands.debug.notStarted", new Object[0]); } long ☃ = MinecraftServer.av(); int ☃ = ☃.ap(); long ☃ = ☃ - this.b; int ☃ = ☃ - this.c; a(☃, ☃, ☃); ☃.c.a = false; a(☃, this, "commands.debug.stop", new Object[] { Float.valueOf((float)☃ / 1000.0F), Integer.valueOf(☃) }); } else { throw new cf("commands.debug.usage", new Object[0]); } } private void a(long ☃, int ☃, MinecraftServer ☃) { File ☃ = new File(☃.d("debug"), "profile-results-" + new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss").format(new Date()) + ".txt"); ☃.getParentFile().mkdirs(); try { FileWriter ☃ = new FileWriter(☃); ☃.write(b(☃, ☃, ☃)); ☃.close(); } catch (Throwable ☃) { a.error("Could not save profiler results to " + ☃, ☃); } } private String b(long ☃, int ☃, MinecraftServer ☃) { StringBuilder ☃ = new StringBuilder(); ☃.append("---- Minecraft Profiler Results ----\n"); ☃.append("// "); ☃.append(d()); ☃.append("\n\n"); ☃.append("Time span: ").append(☃).append(" ms\n"); ☃.append("Tick span: ").append(☃).append(" ticks\n"); ☃.append("// This is approximately ").append(String.format("%.2f", new Object[] { Float.valueOf(☃ / ((float)☃ / 1000.0F)) })).append(" ticks per second. It should be ").append(20).append(" ticks per second\n\n"); ☃.append("--- BEGIN PROFILE DUMP ---\n\n"); a(0, "root", ☃, ☃); ☃.append("--- END PROFILE DUMP ---\n\n"); return ☃.toString(); } private void a(int ☃, String ☃, StringBuilder ☃, MinecraftServer ☃) { List<oo.a> ☃ = ☃.c.b(☃); if ((☃ == null) || (☃.size() < 3)) { return; } for (int ☃ = 1; ☃ < ☃.size(); ☃++) { oo.a ☃ = (oo.a)☃.get(☃); ☃.append(String.format("[%02d] ", new Object[] { Integer.valueOf(☃) })); for (int ☃ = 0; ☃ < ☃; ☃++) { ☃.append("| "); } ☃.append(☃.c).append(" - ").append(String.format("%.2f", new Object[] { Double.valueOf(☃.a) })).append("%/").append(String.format("%.2f", new Object[] { Double.valueOf(☃.b) })).append("%\n"); if (!☃.c.equals("unspecified")) { try { a(☃ + 1, ☃ + "." + ☃.c, ☃, ☃); } catch (Exception ☃) { ☃.append("[[ EXCEPTION ").append(☃).append(" ]]"); } } } } private static String d() { String[] ☃ = { "Shiny numbers!", "Am I not running fast enough? :(", "I'm working as hard as I can!", "Will I ever be good enough for you? :(", "Speedy. Zoooooom!", "Hello world", "40% better than a crash report.", "Now with extra numbers", "Now with less numbers", "Now with the same numbers", "You should add flames to things, it makes them go faster!", "Do you feel the need for... optimization?", "*cracks redstone whip*", "Maybe if you treated it better then it'll have more motivation to work faster! Poor server." }; try { return ☃[((int)(System.nanoTime() % ☃.length))]; } catch (Throwable ☃) {} return "Witty comment unavailable :("; } public List<String> a(MinecraftServer ☃, m ☃, String[] ☃, cj ☃) { if (☃.length == 1) { return a(☃, new String[] { "start", "stop" }); } return Collections.emptyList(); } }
MCLabyMod/LabyMod-1.9
x.java
11
public static void splitTheBlop(Monster curr) { if (!curr.canSplit()) { players[BLOPSPLIT] = new Player(); // Assuming Player is the appropriate class for players array curr.setHealth((int)(Math.random() * (101 - 50 + 1) + 50)); curr.setCanSplit(true); } else { if (curr.getHealth() == 100) { int Number = (int)(Math.random() * (76 - 25 + 1) + 25); curr.damage(Number); players[BLOPSPLIT] = new Blop(curr.getRow(), curr.getCol(), playerImages[4]); curr.setCanSplit(false); } } }
1588974/Array-List
e.java
12
import java.io.InputStream; import java.io.FileInputStream; public class Main { public static void main(String args[]) { try { // file input.txt is loaded as input stream // input.txt file contains: // This is a content of the file input.txt InputStream input = new FileInputStream("input.txt"); System.out.println("Data in the file: "); // Reads the first byte int i = input.read(); while(i != -1) { System.out.print((char)i); // Reads next byte from the file i = input.read(); } input.close(); } catch(Exception e) { e.getStackTrace(); } } }
Hansajith98/hacktoberfest2021-Excluded
Java/FileTextAsInputStream.java
13
// Program to print BFS traversal from a given // source vertex. BFS(int s) traverses vertices // reachable from s. #include<bits/stdc++.h> using namespace std; // This class represents a directed graph using // adjacency list representation class Graph { int V; // No. of vertices // Pointer to an array containing adjacency // lists vector<list<int>> adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); // prints BFS traversal from a given source s void BFS(int s); }; Graph::Graph(int V) { this->V = V; adj.resize(V); } void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v’s list. } void Graph::BFS(int s) { // Mark all the vertices as not visited vector<bool> visited; visited.resize(V,false); // Create a queue for BFS list<int> queue; // Mark the current node as visited and enqueue it visited[s] = true; queue.push_back(s); while(!queue.empty()) { // Dequeue a vertex from queue and print it s = queue.front(); cout << s << " "; queue.pop_front(); // Get all adjacent vertices of the dequeued // vertex s. If a adjacent has not been visited, // then mark it visited and enqueue it for (auto adjecent: adj[s]) { if (!visited[adjecent]) { visited[adjecent] = true; queue.push_back(adjecent); } } } } // Driver program to test methods of graph class int main() { // Create a graph given in the above diagram Graph g(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); cout << "Following is Breadth First Traversal " << "(starting from vertex 2) \n"; g.BFS(2); return 0; }
manan-shxrma/dsalgo
graphs/bFSgraph.cpp
14
class Solution { public List<List<Integer>> threeSum(int[] nums) { if (nums.length < 3) return new ArrayList<>(); List<List<Integer>> ans = new ArrayList<>(); Arrays.sort(nums); for (int i = 0; i + 2 < nums.length; ++i) { if (i > 0 && nums[i] == nums[i - 1]) continue; // choose nums[i] as the first num in the triplet, // and search the remaining nums in [i + 1, n - 1] int l = i + 1; int r = nums.length - 1; while (l < r) { final int sum = nums[i] + nums[l] + nums[r]; if (sum == 0) { ans.add(Arrays.asList(nums[i], nums[l++], nums[r--])); while (l < r && nums[l] == nums[l - 1]) ++l; while (l < r && nums[r] == nums[r + 1]) --r; } else if (sum < 0) { ++l; } else { --r; } } } return ans; } }
Next-Gen-UI/Code-Dynamics
Leetcode/0015. 3Sum/0015.java
15
// AI class, a main component of the CFM Project // This component is really the brains of the program since it is used to simplify expressions and solve equations // and to determine if student answers are algebraically equivalent with the correct answers. // By G. Baugher package cfm_files; import java.util.Scanner; public class AI { static String origText, origValue, expression, messages = ""; static String[] answer = { "", "" }; static double enteredValue; static Term[] overallExpr = initArrayOfTerms(); static boolean equation = false; public static class Term { // Creates a class for representing algebraic terms, each having a coefficient, a variable, and an exponent. public double coeff; public char variable; public int expon; public Term( double coef, char var, int expo ) { this.coeff = coef; this.variable = var; this.expon = expo; } public double getCoeff() { return coeff; } public char getVar() { return variable; } public int getExpon() { return expon; } public void setCoeff(double coef) { coeff = coef; } public void setVar(char var) { variable = var; } public void setExpon(int expo) { expon = expo; } public Term() { coeff = 0.0; variable = ' '; expon = 0; }; } public static Term initTerm(Term term) { term.setCoeff(0.0); term.setVar(' '); term.setExpon(0); return term; } public static Term[] initArrayOfTerms( ) { Term[] arrayOfTerms = new Term[19]; int i; for (i=0; i<19; i++) { arrayOfTerms[i] = new Term(); initTerm( arrayOfTerms[i] ); } return arrayOfTerms; } public static int numNonEmptyTerms ( Term[] inputExpr ) { int numOfLastTerm = inputExpr.length-1; boolean lastEmptyTerm = false; while (!lastEmptyTerm) { if ((inputExpr[numOfLastTerm].coeff == 0) && (inputExpr[numOfLastTerm].variable == ' ')) { numOfLastTerm--; if (numOfLastTerm == 0) lastEmptyTerm = true; } else lastEmptyTerm = true; } return numOfLastTerm + 1; } public static String elimOrAddSigns( String expression) { // Eliminates initial plus signs or terminal signs in an expression and also adds 1's before variables int i, len = expression.length(), count = 0; char ch; if ( expression.length() != 0 ) { // Do nothing if expression is void. if ( expression.length() == 1 ) { // Check if single character expression has no number or variable ch = expression.charAt(0); if ( "=+-*/()[]{}^.–".indexOf(ch) != -1 ) { expression = ""; messages += "Error - incorrect expression: no algebra terms or numbers in the expression. "; }; } else { while ((len > 1) && (count < len)) { // System.out.println( "len: " + len + " count: " + count ); count+=2; // Remove any initial '+' sign or any '+' or '-' sign at end of expression. len = expression.length(); if ((expression.charAt(len-1) == '+') || (expression.charAt(len-1) == '-')) expression = expression.substring(0,len-1); if (expression.charAt(0) == '+') expression = expression.substring(1); // Add coefficient of 1 in front of any letter not already having a coefficient if (Character.isLetter( expression.charAt(0) )) expression = "1" + expression; for ( i = 0; i < expression.length() - 2; i++ ) { ch = expression.charAt(i); if ((( ch == '+') || (ch == '-')) || ((ch == '(') || (ch == ')')) ) if (Character.isLetter( expression.charAt(i+1) )) expression = expression.substring(0,i+1) + "1" + expression.substring(i+1); }; }; } } return expression; } public static String removeSpaces( String exp ) { int i; exp = exp.trim(); while (exp.indexOf(' ') != -1) { for(i=0; i<exp.length(); i++) { if (exp.charAt(i)==' ') { exp = exp.substring(0,i) + exp.substring(i+1); } } }; return exp; } public static String prepareEquation( String expression ) { int i, count = 0, location = 0; equation = false; String leftSide = "", rightSide = ""; // Determine if there are equal signs (and if more than one) and if one, set equation to true. for (i=0; i < expression.length(); i++ ) { if ( expression.charAt(i) == '=' ) { count++; location = i; }; }; equation = (count == 1); if (count > 1) { messages += "Error - incorrect expression: multiple equal signs. "; } // If equation, divide into two sides and eliminate initial plus signs or terminal signs in leftSide or rightSide expressions if (equation) { leftSide = expression.substring(0,location); rightSide = expression.substring(location+1); System.out.println("Left Side: " + leftSide + " Right Side: " + rightSide ); leftSide = elimOrAddSigns( leftSide ); rightSide = elimOrAddSigns( rightSide ); expression = leftSide + '=' + rightSide; }; return expression; } public static String removeDoubleSigns( String expression ) { boolean completed = false; int j; char ch; String twoChar, tempString = expression; // Change ++ to +, +- or -+ to -, and -- to +, if any of these are in the string if ( expression.length() > 2 ) { while ( !completed) { for ( j = 0; j < expression.length() - 1; j++ ) { twoChar = expression.substring(j,j+2); ch = '#'; if (twoChar.compareTo("++") == 0) { ch = '+'; messages += "Double plus signs should be changed to + only. "; }; if ((twoChar.compareTo("+-") == 0) || (twoChar.compareTo("-+") == 0)) { ch = '-'; messages += "+- or -+ should be changed to - only. "; }; if (twoChar.compareTo("--") == 0) { ch = '+'; messages += "Double minus signs should be changed to a + sign. "; }; if (ch != '#') { expression = expression.substring(0,j) + ch + expression.substring(j+2); //j--; } }; if ( tempString.compareTo(expression) == 0 ) completed = true; tempString = expression; }; } return expression; } public static String removeOtherCharacters( String expression ) { int i = 0; char ch; boolean ok; if ( expression.length() > 0 ) while ( i < expression.length()-1 ) { ok = false; ch = expression.charAt(i); if ((Character.isDigit(ch)) || (Character.isLetter(ch))) ok = true; if ("=+-*/()[]{}^.–".indexOf(ch) != -1) ok = true; if (!ok) { System.out.println( "Error - expression has an unacceptable character: " + ch + " (character removed). " ); expression = expression.substring(0,i) + expression.substring(i+1); }; i++; }; return expression; } public static String removeTermsWithZeroCoefficients( String expression ) { // This needs to be written or the code written and added into combineLikeTerms() or determineExpr() return expression; } public static String prepareExpOrEq( String origText ) { // Prepares the string in various ways, detects unwanted characters, determines if equation, etc. // Remove any spaces and switch upper to lower case letters String expression = removeSpaces( origText ).toLowerCase(); // Detect and remove characters other than numbers, letters, operation signs, equal signs, and parentheses or brackets. expression = removeOtherCharacters( expression ); // Remove any double signs such as '--' or '+-' expression = removeDoubleSigns( expression ); // Eliminate initial plus signs or terminal signs in the whole expression or add 1's before variables if no coefficient expression = elimOrAddSigns( expression ); // If equation, prepare the two sides separately expression = prepareEquation( expression ); // System.out.println("Messages: " + messages); return expression; } // end of prepareExpOrEq public static Term[] determineExpr( String origExpr, int beginPos, int endPos) { // Analyzes the string character by character and converts to an array of Terms boolean nowExpon = false, prevIsDigit = false, prevIsLetter = false; // (assuming no parentheses in the expression) int i, index, signMultiplier = 1, numOfTerm = 0; char ch; String numStr = ""; double number = 0; double coeff[] = new double[19]; char variable[] = new char[19]; int expon[] = new int[19]; for ( index = 0; index < 19; index++ ) { coeff[index] = 0; variable[index] = ' '; expon[index] = 0; }; Term[] exprAsArrayOfTerms = initArrayOfTerms(); i = beginPos; ch = origExpr.charAt(i); if ((ch == '+') || ( ch == '-')) { if (ch == '-') signMultiplier = -1; i++; }; while ( i < endPos ) { ch = origExpr.charAt(i); if ( !(Character.isDigit(ch) || (ch == '.') ) && prevIsDigit) { number = Double.parseDouble(numStr); if (nowExpon) { expon[numOfTerm] = (int) number; nowExpon = false; } else { coeff[numOfTerm] = signMultiplier*number; }; numStr = ""; prevIsDigit = false; }; if (Character.isDigit(ch) || (ch == '.')) { numStr += ch; prevIsDigit = true; }; if (Character.isLetter(ch)) { expon[numOfTerm] = 1; if (prevIsLetter) messages += "Error: adjacent letters found. "; else { variable[numOfTerm] = ch; prevIsLetter = true; }; } else { prevIsLetter = false; }; if (ch == '^') { if (nowExpon) messages += "Error: multiple adjacent exponent symbols (^) found. "; if (!(prevIsLetter)) messages += "Error: exponent not preceeded by a variable. "; nowExpon = true; }; if ((ch == '+') || (ch == '-')) { exprAsArrayOfTerms[numOfTerm].setCoeff(coeff[numOfTerm]); exprAsArrayOfTerms[numOfTerm].setVar(variable[numOfTerm]); exprAsArrayOfTerms[numOfTerm].setExpon(expon[numOfTerm]); numOfTerm++; if (ch == '+') signMultiplier = 1; if (ch == '-') signMultiplier = -1; }; if (i == endPos-1) { if (Character.isDigit(ch)) { number = Double.parseDouble(numStr); if (nowExpon) { expon[numOfTerm] = (int) number; exprAsArrayOfTerms[numOfTerm].setCoeff(coeff[numOfTerm]); exprAsArrayOfTerms[numOfTerm].setVar(variable[numOfTerm]); exprAsArrayOfTerms[numOfTerm].setExpon(expon[numOfTerm]); } else { exprAsArrayOfTerms[numOfTerm].setCoeff(signMultiplier*number); exprAsArrayOfTerms[numOfTerm].setVar(' '); exprAsArrayOfTerms[numOfTerm].setExpon(0); }; }; if (Character.isLetter(ch)) { expon[numOfTerm] = 1; exprAsArrayOfTerms[numOfTerm].setCoeff(coeff[numOfTerm]); exprAsArrayOfTerms[numOfTerm].setVar(variable[numOfTerm]); exprAsArrayOfTerms[numOfTerm].setExpon(expon[numOfTerm]); }; System.out.println( "At endPos-1 which is " + i + " Ch: " + ch ); System.out.print( "numOfTerm: " + numOfTerm + " Number: " + number + " Expression building: "); displayExpr( exprAsArrayOfTerms ); }; i++; }; return exprAsArrayOfTerms; } // end of determineExpr public static void displayExpr( Term[] expr ) { // Used various places where expressions are to be displayed in the console int index, num = numNonEmptyTerms( expr ); for (index = 0; index < num; index++ ) { System.out.print( " " + expr[index].coeff ); if ( expr[index].expon != 0 ) { System.out.print( expr[index].variable + "^" + expr[index].expon ); } if (index != num-1) System.out.print( " +" ); else System.out.println(" "); }; } public static String convertToStr( Term[] expr ) { // Used several places to convert an array of Terms into a string int i, numOfTerms = numNonEmptyTerms( expr ); String newExpr = ""; for (i=0; i < numOfTerms; i++) { // Build new expression after distributing if ( expr[i].expon == 0 ) { newExpr += Double.toString( expr[i].coeff ); } else { newExpr += Double.toString( expr[i].coeff ) + expr[i].variable + "^" + Integer.toString((int) expr[i].expon ); } if ( i < numOfTerms - 1) newExpr += "+"; } return newExpr; } public static Term[] distributeMonomial( Term[] monomial, Term[] insideExpr) { // Distributes a single term (monomial) to an expression int index; Term[] resultExpr = initArrayOfTerms(); for (index = 0; index < numNonEmptyTerms( insideExpr ); index++ ) { resultExpr[index].setCoeff( monomial[0].coeff*insideExpr[index].coeff ); char monVar = monomial[0].variable; char insVar = insideExpr[index].variable; if ((monVar == insVar)||(insVar == 32)) { resultExpr[index].setVar(monomial[0].variable); resultExpr[index].setExpon( monomial[0].expon + insideExpr[index].expon); } else { resultExpr[index].variable = insideExpr[index].variable; resultExpr[index].expon = insideExpr[index].expon; }; }; return resultExpr; } public static Term[] deleteTerm( int index, Term[] expression ) { // To eliminate the "processed" highExpon term from the input expression int m, numOfTerms = numNonEmptyTerms( expression ); if ( index == numOfTerms - 1 ) { initTerm( expression[ index ] ); } else { for ( m = index; m < numOfTerms-1; m++ ) { expression[m].setCoeff( expression[m+1].coeff ); expression[m].setVar( expression[m+1].variable ); expression[m].setExpon( expression[m+1].expon ); }; initTerm( expression[numOfTerms-1] ); }; return expression; } public static Term[] combineLikeTerms( Term[] inputExpr) { // Starting with the highest exponent, searches for like terms and combines int i, j, highExpon, highIndex = 0, origNumOfTerms, numOfTerms; double sumOfCoeffs; //char highVar; Term[] outputExpr = initArrayOfTerms(); origNumOfTerms = inputExpr.length; numOfTerms = numNonEmptyTerms( inputExpr ); i = 0; while ( ( i < origNumOfTerms ) && ( numOfTerms != 0 ) ) { numOfTerms = numNonEmptyTerms( inputExpr ); // set the high exponent term to be the first term highExpon = inputExpr[0].expon; //highVar = inputExpr[0].variable; highIndex = 0; if (numOfTerms > 0) { for ( j = 1; j < numOfTerms; j++ ) { if (highExpon < inputExpr[j].expon ) { // add a condition of the variables being the same highExpon = inputExpr[j].getExpon(); highIndex = j; //highVar = inputExpr[j].getVar(); }; }; // Stores highest exponent term in outputExpr, then removes it from the inputExpr array outputExpr[i].setVar( inputExpr[highIndex].variable ); outputExpr[i].setExpon( inputExpr[highIndex].expon ); outputExpr[i].setCoeff( inputExpr[highIndex].coeff ); inputExpr = deleteTerm( highIndex, inputExpr ); numOfTerms = numNonEmptyTerms( inputExpr ); }; // To look for a term that is "like" the outputExpr[i] term and combine it for ( j = 0; j < numOfTerms; j++ ) { if (( outputExpr[i].variable == inputExpr[j].variable ) && ( outputExpr[i].expon == inputExpr[j].expon)) { // To store the combined term in the output expression sumOfCoeffs = inputExpr[j].coeff + outputExpr[i].coeff; outputExpr[i].setCoeff( sumOfCoeffs ); // To eliminate the "processed" like term from the input expression inputExpr = deleteTerm( j, inputExpr ); numOfTerms = numNonEmptyTerms( inputExpr ); }; }; // End of for j Loop i++; } return outputExpr; } // End of combineLikeTerms public static Term[] simpSingleParExpr( String expression ) { // Handles when the expression has one set of parentheses int i, j, k, l, m = 0, n = 0; String newExpr = "", beginStr = "", endStr = ""; boolean parError = false, endMultiplier = false; Term[] expressionList = initArrayOfTerms(); Term[] nestExpr = initArrayOfTerms(); Term[] multiplierTerm = initArrayOfTerms(); Term[] resultExpr = initArrayOfTerms(); // Determine positions of open and close parentheses ParPos pp = new ParPos(); pp.determParPos(expression); // Process parentheses except for any term after the parentheses k = pp.Open1; i = expression.lastIndexOf('+', k); j = expression.lastIndexOf('-', k); l = expression.lastIndexOf('–', k); if ((j!=-1) || (l!=-1)) j = Math.max(j, l); if ((i!=-1)||(j!=-1)) { k = Math.max(i, j); multiplierTerm = determineExpr( expression, k, pp.Open1); } else { multiplierTerm = determineExpr( expression, 0, pp.Open1); k = 0; }; if (k != 0) beginStr = expression.substring(0,k) + "+"; nestExpr = determineExpr( expression, pp.Open1+1, pp.Close1 ); if (numNonEmptyTerms(multiplierTerm) == 1) { resultExpr = distributeMonomial( multiplierTerm, nestExpr); }; // Determine if any final term to distribute and distribute it; determine any trailing added part of expression if (pp.Close1 < expression.length()-1) { i = expression.indexOf('+',pp.Close1); j = expression.indexOf('-',pp.Close1); l = expression.lastIndexOf('–',pp.Close1); m = pp.Close1; if (i!=-1) m = i; if ((j!=-1) || (l!=-1)) j = Math.max(j, l); if (j!=-1) { n = j; if (i!=-1) m = Math.min( m, n ); else m = j; }; if (( i == -1 ) && ( j == -1 )) { multiplierTerm = determineExpr( expression, pp.Close1+1, expression.length() ); endMultiplier = true; endStr = ""; } else { multiplierTerm = determineExpr( expression, pp.Close1+1, m); endMultiplier = true; if (m>pp.Close1) endStr = "+" + expression.substring( m ); else endStr = "+" + expression.substring(m+1); }; if (endMultiplier) if ((numNonEmptyTerms(multiplierTerm) == 1) && (multiplierTerm[0].coeff != 0)) { resultExpr = distributeMonomial( multiplierTerm, resultExpr); }; }; // Combine all parts and prepare expression and combine like terms newExpr = convertToStr( resultExpr ); expression = beginStr + newExpr + endStr; expression = prepareExpOrEq( expression ); expressionList = determineExpr( expression, 0, expression.length() ); expressionList = combineLikeTerms ( expressionList ); if (parError) System.out.println( "Incorrect entry. Try again." ); return expressionList; } // end of simpSinglePar public static Term[] addTwoExpressions( Term[] exp1, Term[] exp2 ) { // Adds two expressions (arrays of terms) int i, numOfTerms; String newExpr = ""; Term[] expression = initArrayOfTerms(); numOfTerms = numNonEmptyTerms( exp1 ); for (i=0; i < numOfTerms; i++) { // Build first part of new expression if (( exp1[i].expon == 0 ) && (exp1[i].coeff != 0 )) { newExpr += Double.toString( exp1[i].coeff ); } else { newExpr += Double.toString( exp1[i].coeff ) + exp1[i].variable + "^" + Integer.toString((int) exp1[i].expon ); } if ( i < numOfTerms - 1) newExpr += "+"; } newExpr += "+"; numOfTerms = numNonEmptyTerms( exp2 ); for (i=0; i < numOfTerms; i++) { // Build second part of new expression if (( exp2[i].expon == 0 ) && (exp2[i].coeff != 0 )) { newExpr += Double.toString( exp2[i].coeff ); } else { if ((exp2[i].variable != ' ') || (exp2[i].coeff != 0 )) newExpr += Double.toString( exp2[i].coeff ) + exp2[i].variable + "^" + Integer.toString((int) exp2[i].expon ); } if ( i < numOfTerms - 1) newExpr += "+"; } newExpr = prepareExpOrEq( newExpr ); expression = determineExpr( newExpr, 0, newExpr.length() ); expression = combineLikeTerms( expression ); return expression; } static class ParPos { int Open1 = -1, Open2 = -1, Close1 = -1, Close2 = -1; boolean parError = false; public ParPos determParPos( String exp ) { int i, j; char ch; ParPos pp = new ParPos(); for ( i = 0; i < exp.length(); i++ ) { ch = exp.charAt(i); if ((ch == '(') && (Open1 == -1)) { Open1 = i; } if ((ch == '(') && ((Open1 != -1) && (Open1 != i))) Open2 = i; }; j = exp.indexOf(')'); if (j != -1) if (j < Open1) { parError = true; System.out.println( "Error: closing parentheses before opening parentheses."); } else { Close1 = j; }; j = exp.indexOf(')',j+1); if (j != -1) if ((j < Open2) || (j < Open1)) { parError = true; System.out.println( "Error: closing parentheses before opening parentheses."); } else { Close2 = j; }; return pp; } public void setOpen1( int position ) { Open1 = position; }; public void setOpen2( int position ) { Open2 = position; }; public void setClose1( int position ) { Close1 = position; }; public void setClose2( int position ) { Close2 = position; }; } public static Term[] simpDoubleParExpr( String origExpression ) { // Handles when the expression has two sets of parentheses by use of simpSinglePar twice int k; String beginExpr = "", endExpr = ""; Term[] firstExpr = initArrayOfTerms(); Term[] secondExpr = firstExpr; Term[] expression = firstExpr; // Determine end of first set of parentheses ParPos pp = new ParPos(); pp.determParPos(origExpression); k = pp.Close1; beginExpr = origExpression.substring(0,k+1); firstExpr = combineLikeTerms(simpSingleParExpr( beginExpr )); endExpr = origExpression.substring(k+1); secondExpr = combineLikeTerms(simpSingleParExpr( endExpr )); expression = addTwoExpressions( firstExpr, secondExpr ); if (pp.parError) System.out.println( "Incorrect entry. Try again." ); expression = combineLikeTerms( expression ); return expression; } // End of simpDoublePar public static Term[] simpNestParExpr( String expression ) { // Handles expressions with one set of parentheses inside another set of parentheses String newExpr = ""; Term[] expressionTerms = initArrayOfTerms(); Term[] nestExpr = expressionTerms; ParPos pp = new ParPos(); pp.determParPos(expression); // Simplify inner nested parentheses newExpr = expression.substring( pp.Open1+1, pp.Close2); newExpr = prepareExpOrEq( newExpr ); nestExpr = simpSingleParExpr( newExpr ); // Build new string expression after combining strings newExpr = convertToStr( nestExpr ); expression = expression.substring(0,pp.Open1) + "(" + newExpr + ")" + expression.substring( pp.Close2+1 ); expression = prepareExpOrEq( expression ); // Simplify complete expression string expressionTerms = simpSingleParExpr( expression ); if (pp.parError) System.out.println( "Incorrect entry. Try again." ); return expressionTerms; } // End of simpNestParExpr public static Term[] simpAdjacParExpr( String exp ) { // Handles expressions with two parentheses adjacent to each other (where they must be multiplied) int i, j, k = 0, l, len, endLen, numOfTerms1, numOfTerms2; double multiplier = 1; String beginStr = "", endStr = ""; boolean multiplyingDone = false, backDistribute = false; char ch; Term[] expression = initArrayOfTerms(); Term[] multiplierExpr = expression; Term[] firstExpr = expression; Term[] tempExpr = expression; Term[] secondExpr = expression; Term[] resultExpr = expression; Term[] endMultiplierTerm = expression; exp = prepareExpOrEq( exp ); len = exp.length(); // Determine positions of openings and closings of parentheses ParPos pp = new ParPos(); pp.determParPos(exp); // Handle any part of the expression before the first parentheses if (pp.Open1 != 0) { beginStr = exp.substring( 0, pp.Open1); // If just one character before opening parentheses, set multiplier to -1 if a negative sign or to a digit if a digit if (beginStr.length() == 1) { ch = beginStr.charAt(0); if (ch == '-') multiplier = -1; if (Character.isDigit(ch)) multiplier = Double.valueOf( ch ) - 48; beginStr = ""; multiplierExpr[0].setCoeff( multiplier ); }; // If multiple characters before opening parentheses, determine if any are multipliers to the parentheses if (beginStr.length() > 1) { k = pp.Open1; i = exp.lastIndexOf('+', k); j = exp.lastIndexOf('-', k); l = exp.lastIndexOf('–', k); if ((j!=-1) || (l!=-1)) j = Math.max(j, l); if ((i!=-1)||(j!=-1)) { k = Math.max(i, j); multiplierExpr = determineExpr( exp, k, pp.Open1); } else { multiplierExpr = determineExpr( exp, 0, pp.Open1); k = 0; }; if (k != 0) beginStr = exp.substring(0,k) + "+"; }; }; // Handle any part of the expression after the parentheses if (pp.Close2 < len-1) { endStr = exp.substring( pp.Close2+1, len); endLen = endStr.length(); if (endLen == 1) { ch = endStr.charAt(0); if (Character.isDigit(ch)) { multiplier = Integer.valueOf( ch ) - 48; backDistribute = true; endMultiplierTerm = determineExpr( endStr, 0, 1); }; }; if (endLen > 1) { i = endStr.indexOf('+'); j = endStr.indexOf('-'); k = -1; if ((i==-1) && (j==-1)) { endMultiplierTerm = determineExpr( endStr, 0, endLen); backDistribute = true; } else { if (i!=-1) { k = i; if (j!=-1) k = Math.min( i, j ); } else { if (j!=-1) k = j; }; }; if (k!=-1) { if (k>0) { endMultiplierTerm = determineExpr( endStr, 0, k); backDistribute = true; endStr = endStr.substring(k); } else if (k==0) { backDistribute = false; }; } else { endMultiplierTerm = determineExpr( endStr, 0, endStr.length()-1 ); }; }; }; // Perform the multiplication of the two expressions in parentheses firstExpr = determineExpr( exp, pp.Open1, pp.Close1 ); firstExpr = combineLikeTerms( firstExpr ); numOfTerms1 = numNonEmptyTerms( firstExpr ); secondExpr = determineExpr( exp, pp.Open2, pp.Close2 ); secondExpr = combineLikeTerms( secondExpr ); numOfTerms2 = numNonEmptyTerms( secondExpr ); if (numOfTerms1 == 1) { resultExpr = distributeMonomial( firstExpr, secondExpr ); multiplyingDone = true; }; if ((numOfTerms2 == 1) && (!multiplyingDone)) { resultExpr = distributeMonomial( secondExpr, firstExpr ); multiplyingDone = true; }; if (!multiplyingDone) { for (i=0; i < 9; i++) initTerm( resultExpr[i] ); for (j = 0; j < numOfTerms1; j++ ) { Term[] term = initArrayOfTerms(); term[0] = firstExpr[j]; tempExpr = distributeMonomial( term, secondExpr ); resultExpr = addTwoExpressions( resultExpr, tempExpr ); }; multiplyingDone = true; }; // Distribute any multiplier to the result of above parentheses multiplication, and add in beginStr and endExpr if (pp.Open1 != 0) { resultExpr = distributeMonomial( multiplierExpr, resultExpr ); }; if (backDistribute) { resultExpr = distributeMonomial( endMultiplierTerm, resultExpr ); }; if (beginStr.length() > 0) { tempExpr = determineExpr( beginStr, 0, beginStr.length() ); resultExpr = addTwoExpressions( tempExpr, resultExpr ); }; if (endStr.length() > 0) { tempExpr = determineExpr( endStr, 0, endStr.length() ); resultExpr = addTwoExpressions( tempExpr, resultExpr ); }; expression = combineLikeTerms( resultExpr ); if (pp.parError) System.out.println( "Incorrect entry. Try again." ); return expression; } // end of simpAdjParExpr public static Term[] roundCoeffs( Term[] expression ) { // Used to handle roundoff errors or to limit the digits displayed after the decimal point int i, numOfTerms = numNonEmptyTerms( expression ); Term[] outputExpr = initArrayOfTerms(); for (i=0; i < numOfTerms; i++) { outputExpr[i].setCoeff( Math.rint( expression[i].getCoeff()*1000 )/1000 ); outputExpr[i].setVar( expression[i].getVar() ); outputExpr[i].setExpon( expression[i].getExpon() ); } return outputExpr; } public static String add1inFrontOfParentheses( String expression, ParPos pp ) { int i, j, k; if (pp.Open1 != -1) { i = expression.lastIndexOf('+', pp.Open1); j = expression.lastIndexOf('-', pp.Open1); k = pp.Open1-1; if ((k==i) || (k==j)) { expression = expression.substring(0,k+1) + "1" + expression.substring(k+1); pp.setOpen1( pp.Open1 + 1 ); pp.setClose1( pp.Close1 + 1 ); if (pp.Open2 != -1) { pp.setOpen2( pp.Open2 + 1 ); pp.setClose2( pp.Close2 + 1 ); } }; }; if (pp.Open2 != -1) { i = expression.lastIndexOf('+',pp.Open2); j = expression.lastIndexOf('-',pp.Open2); k = pp.Open2-1; if ((k==i) || (k==j)) { expression = expression.substring(0,k+1) + "1" + expression.substring(k+1); pp.setOpen2( pp.Open2 + 1 ); pp.setClose2( pp.Close2 + 1 ); }; }; return expression; } public static Term[] simplifyExpr( String expression ) { // The main component to distinguish the type of expression and send it to a particular method to simplify it String type = ""; boolean parError = false; Term[] result = initArrayOfTerms(); expression = prepareExpOrEq( expression ); // Determine positions of parentheses (and if correctly ordered or has error) ParPos pp = new ParPos(); pp.determParPos(expression); parError = pp.parError; // Determine the type of expression: if no parentheses, single, double, or nested. if ((expression.indexOf('(')==-1) && (expression.indexOf(')')==-1)) type = "noPar"; else if ((pp.Open2 == -1) && (pp.Close2 == -1)) type = "singlePar"; if (( pp.Open2 != -1) && (pp.Close1 != -1)) if (pp.Open2 < pp.Close1) type = "nestedPar"; else type = "doublePar"; if (pp.Close1 == pp.Open2 - 1) { type = "adjacentPar"; }; // Place a 1 in front of parentheses when parentheses are added or subtracted expression = add1inFrontOfParentheses( expression, pp ); System.out.println( "Expression: " + expression ); System.out.print( " Type: " ); // Pass the expression to the appropriate method to simplify it switch( type ) { case "noPar": { System.out.println( "No Parentheses"); result = determineExpr( expression, 0, expression.length() ); result = combineLikeTerms( result ); }; break; case "singlePar": { System.out.println( "Single Parentheses"); result = simpSingleParExpr( expression ); }; break; case "doublePar": { System.out.println( "Double Parentheses"); result = simpDoubleParExpr( expression ); }; break; case "nestedPar": { System.out.println( "Nested Parentheses"); result = simpNestParExpr( expression ); }; break; case "adjacentPar": { System.out.println( "Adjacent Parentheses"); result = simpAdjacParExpr( expression ); }; break; default: System.out.println( "No discernable type" ); }; result = combineLikeTerms( result ); result = roundCoeffs( result ); if (!parError) { System.out.print( "\nFinal Simplified Expression: "); displayExpr( result ); } else { System.out.println( "Incorrect entry. Try again." ); }; return result; } // End of simplifyExpr public static double evaluateExpr( Term[] expression, double value ) { // Given a value for the variable, this method evaluates a whole expression double termVal = 0, tempVal = 1, answer = 0; int index, i, numOfTerms = numNonEmptyTerms( expression ); for (index=0; index < numOfTerms; index++) { termVal = 0; tempVal = 1; for (i=0; i<expression[index].expon; i++) tempVal *= value; termVal = expression[index].coeff*tempVal; answer = answer + termVal; }; return answer; } // End of evaluateExpr public static String simplifyEquation( String equationStr ) { // Converts left & right sides to expression, combines on left side, converts equation back to string int location; String leftSide = "", rightSide = "", simplifiedEquation = ""; Term[] leftExpr = initArrayOfTerms(); Term[] rightExpr = leftExpr; Term[] combinedExpr = leftExpr; Term[] negOne = determineExpr( "-1", 0, 2); equationStr = removeSpaces( equationStr ); location = equationStr.indexOf('='); leftSide = equationStr.substring(0,location); rightSide = equationStr.substring(location+1); //System.out.println( "left: " + leftSide + " right: " + rightSide); leftSide = prepareExpOrEq( leftSide ); rightSide = prepareExpOrEq( rightSide ); //System.out.println( "prepped left: " + leftSide + " prepped right: " + rightSide); leftExpr = simplifyExpr( leftSide ); rightExpr = simplifyExpr( rightSide ); //System.out.println( "simplified left: " + convertToStr( leftExpr ) + " simplified right: " + convertToStr( rightExpr ) ); combinedExpr = addTwoExpressions( leftExpr, distributeMonomial( negOne, rightExpr ) ); //System.out.print( "Combined Sides: "); displayExpr( combinedExpr ); if ( numNonEmptyTerms( combinedExpr ) > 0 ) simplifiedEquation = convertToStr( combinedExpr ); else simplifiedEquation = "0"; simplifiedEquation = prepareExpOrEq( simplifiedEquation + "=0" ); return simplifiedEquation; } // End of simpEquation public static String[] solveEquation( String equation ) { // Once equation is simplified, this method solves it and returns answerwers in an array of type String // If equation has degree < 3, equation is solved using -b/a (linear) or by quadratic formula (quadratic) int i, location, degree, numOfTerms; double[] a = new double[19]; Term[] expression = initArrayOfTerms(); String[] answer = new String[2]; for (i=0; i<2; i++) { answer[i] = ""; }; location = equation.indexOf('='); expression = determineExpr( equation, 0, location); numOfTerms = numNonEmptyTerms( expression ); degree = 0; for (i=0; i < numOfTerms; i++) { if (expression[i].expon > degree) degree = expression[i].expon; }; if (degree == 0) { if (expression[0].coeff == 0) answer[0] = "All real numbers"; else answer[0] = "No solutions"; }; if (degree == 1) { answer[0] = String.valueOf( -1*expression[1].coeff / expression[0].coeff ); }; if (degree == 2) { for ( i=0; i < numOfTerms; i++) { if (expression[i].expon == 2) a[2] = expression[i].coeff; if (expression[i].expon == 1) a[1] = expression[i].coeff; if (expression[i].expon == 0) a[0] = expression[i].coeff; }; if (a[1]*a[1]-4*a[2]*a[0] >= 0) { answer[0]=String.valueOf((-1*a[1]+Math.sqrt(a[1]*a[1]-4*a[2]*a[0]))/(2*a[2])); answer[1]=String.valueOf((-1*a[1]-Math.sqrt(a[1]*a[1]-4*a[2]*a[0]))/(2*a[2])); } else answer[0] = "No solution in the real numbers."; }; if (degree > 2) answer[0] = "This program currently only solves equations up to degree 2."; return answer; } // End of solveEq public static String round2LineAnswer ( String[] twoLineAnswer ) { double line1ofAnswer = Double.parseDouble(twoLineAnswer[0]), line2ofAnswer = Double.parseDouble(twoLineAnswer[1]); line1ofAnswer = line1ofAnswer*1000; line2ofAnswer = line2ofAnswer*1000; line1ofAnswer = Math.round(line1ofAnswer); line2ofAnswer = Math.round(line2ofAnswer); line1ofAnswer = line1ofAnswer/1000; line2ofAnswer = line2ofAnswer/1000; String result = Double.toString( line1ofAnswer ) + "," + Double.toString( line2ofAnswer ); return result; } public static void AITest() { int i; boolean passed, allPassed = true; String origExpression, finalExpr; String[] equationAnswer; Term[] exprTerms = initArrayOfTerms(); String ANSI_RED = "\u001B[31m"; String ANSI_BLACK = "\u001B[30m"; String[] testName = { "Multiple Signs/Extra Characters", "Multiple Variables", "Expression with 0 Coefficients", "Combine Like Terms - No Parentheses", "Single Parentheses", "Double Parentheses", "Nested Parentheses", "Adjacent Parentheses", "Linear Equation", "Quadratic Equation" }; String[] origExpr = { "-&-2+-@-3x-+(2x++6)-", "4x - 2y + 6 - x + y^2 + y -3","8x - 5 + 0x + 2x^2 - 0 - 7x - 0x^2 +9", "5x - 2x^2 + 4 - 7x + x^2 +1 - 6x^3", "3x+-5(3x-6+4x^2-5x-7)2-5-", "3x+1x(3x-6+4)+5-(2x^2-5x-7)-5--7x", "-3x+x(3x-6+4(2x^2-5x-7)--5)-7x", "--3x+1x(3x-6+4)(2x^2-5x-7)-5-7x", "-3( 2x - 5 ) -7( x + 4 ) = 5( -3x - 2 ) + 9", "3x( 2x - 5 ) - 7( x^2 + 4x - 3 ) = -5x( 3x - 2 ) + 9x^2" }; String[] answer = { "1.0x^1-4.0", "1.0y^2+3.0x^1-1.0y^1+3.0", "2.0x^2+1.0x^1+4.0", "-6.0x^3-1.0x^2-2.0x^1+5.0", "-40.0x^2+23.0x^1+125.0", "1.0x^2+13.0x^1+7.0", "8.0x^3-17.0x^2-39.0x^1", "6.0x^4-19.0x^3-11.0x^2+10.0x^1-5.0", "6.0", "10.188,0.412"}; System.out.println( " A I T E S T : \n" ); for ( i=0; i < testName.length; i++ ) { System.out.println( "TEST: " + testName[i] ); passed = false; origExpression = prepareExpOrEq( origExpr[i] ); if ( origExpression.indexOf('=') == -1 ) { exprTerms = simplifyExpr( prepareExpOrEq( origExpr[i] )); finalExpr = prepareExpOrEq(convertToStr( exprTerms )); System.out.println( "Original expression: " + origExpr[i] + " Simplified expression: " + finalExpr + " Correct Answer: " + answer[i] ); } else { equationAnswer = solveEquation( simplifyEquation( origExpression) ); if ( testName[i] == "Quadratic Equation" ) { // Handle the special case of a quadratic equation with two answers finalExpr = round2LineAnswer( equationAnswer ); } else finalExpr = prepareExpOrEq( equationAnswer[0] ); System.out.println( "Original equation: " + origExpr[i] + " Calculated answer(s): " + finalExpr + " Correct Answer: " + answer[i] ); } if ( finalExpr.compareTo( answer[i] ) == 0) { passed = true; } else { allPassed = false; }; System.out.println( "TEST: " + testName[i] + " Passed = " + ANSI_RED + passed + ANSI_BLACK + "\n"); }; /* The AI code was not designed to handle this test since can only handle two sets of parentheses Double Parentheses with Adjacent; String str5 = "2 - 3x( 4x^2 - 5x ) - 5( x + 2 )( 6x - 9 )", ans5 = "-12.0x^3-15.0x^2-15.0x^1+92.0"; */ System.out.println( "All Tests Passed = " + ANSI_RED + allPassed + ANSI_BLACK + "\n\n"); } public static void main(String[] args) { AITest(); // Input original expression System.out.println("Enter your expression or equation: (only one variable & up to 2 sets of parentheses allowed)"); Scanner sc = new Scanner( System.in ); try { origText = sc.nextLine(); } catch (Exception e) { e.printStackTrace(); } // The method prepareExpOrEq removes spaces, double signs, leading or trailing unnecessary signs, detects unacceptable characters, etc. and determines // whether or not the inputed string is an equation expression = prepareExpOrEq( origText ); if (!equation) overallExpr = simplifyExpr(expression); // Uses various methods to simplify the expression (distributing, combining like terms, etc.) System.out.print( "After simplifying expression: "); displayExpr( overallExpr ); if (!equation) { // After simplifying the expression, this section evaluates the expression for an inputed value of the variable. System.out.println( "\nExpression Evaluator: Enter a value for the variable: \n" ); try { origValue = sc.nextLine(); } catch (Exception e) { e.printStackTrace(); } finally { sc.close(); } enteredValue = Double.valueOf( origValue ); System.out.println( "The expression evaluates to the answer " + evaluateExpr( overallExpr, enteredValue )); } if (equation) { expression = simplifyEquation( expression ); // simpEquation uses simplifyExpr to simplify both sides separately then combine all terms on the left side System.out.println( "Simplified and combined equation: " + expression ); answer = solveEquation( expression ); // solveEq distinguishes the degree of the equation and solves it accordingly (up to degree 2) System.out.print( "Solution Set: { " ); System.out.print( answer[0]); if (answer[1]!="") { System.out.print(", " + answer[1] + " }"); } else { System.out.println( " }" ); }; }; } }
gabaugher/CFM
AI.java
16
import java.net.*; import java.io.*; import java.util.Scanner; class IP{ public static void main(String args[]) throws IOException{ Scanner sc = new Scanner(System.in); System.out.println("Enter the name of website"); String web = sc.nextLine(); try{ InetAddress ip =InetAddress.getByName(web); // ip.getByName(web); System.out.println("The ip is"+ip); } catch(Exception e){ System.out.println(e); } } }
karan9970/Web
IP.java
17
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]; } }
chirag1261/Leetcode
DP/Build Array Where You Can Find The Maximum Exactly K Comparisons
18
package com.example.lf; public final class R { public static final class attr { } public static final class dimen { /** Default screen margins, per the Android Design guidelines. Example customization of dimensions originally defined in res/values/dimens.xml (such as screen margins) for screens with more than 820dp of available width. This would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). */ public static final int activity_horizontal_margin=0x7f040000; public static final int activity_vertical_margin=0x7f040001; } public static final class drawable { public static final int ic_launcher=0x7f020000; } public static final class id { public static final int action_settings=0x7f080002; public static final int rl=0x7f080000; public static final int textview1=0x7f080001; } public static final class layout { public static final int activity_main=0x7f030000; } public static final class menu { public static final int main=0x7f070000; } public static final class string { public static final int action_settings=0x7f050002; public static final int app_name=0x7f050000; public static final int hello_world=0x7f050001; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f060000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f060001; } }
ShriKrishnaTS/JITS-To-Track-a-School-vehicle
R.java
19
package rpgGridBrawl; public class Flee extends GridBrawl { GameData game; public Flee() {} public GameData execute(GameData crt) { game = crt; interact.tellPlayer(7, 4, false); // "Choose a Brawler to be removed from the brawl:" boolean[] cowards = this.sortCowards(game); String options = interact.reportOnFleeOptions(cowards); interact.tellPlayer(options, true); int selection = interact.getFleeSelection(cowards); if (selection == -1) { game.setSuccessfulTurn(false); return game; } interact.tellPlayer(interact.msgBuild(game, 53, selection), false); // "You have selected to remove the " + BRWLRS[selection] + " from the board."; boolean confirm = interact.confirm(); if (!confirm) { game.setSuccessfulTurn(false); return game; } game = clearSpace(game, selection); if (game.isRedsTurn()) game.setRedCanPlace(true); else game.setBlueCanPlace(true); interact.space(); interact.tellPlayer(interact.msgBuild(game, 54, selection), false); // "The " + BRWLRS[selection] + " has fled the brawl!" interact.space(); game = updateLastUsed(game, selection); game.setSuccessfulTurn(true); return game; } private boolean[] sortCowards(GameData game) { int bLength = game.getAllBrawlers().length; boolean[] cowards = new boolean[bLength]; boolean colorMatch = false; for (int b = 0; b < bLength; b++) { Brawler jimbo = game.getBrawler(b); colorMatch = ((game.isRedsTurn() && jimbo.isRed()) || (!game.isRedsTurn() && jimbo.isBlue())); if ((jimbo instanceof Character) && !colorMatch) cowards[b] = false; // you can't make your opponent's Characters flee. else if (jimbo.isOnBoard() && (1 == jimbo.getFloor()) && !jimbo.isUsedLast()) cowards[b] = true; } return cowards; } } // end of Flee class
JKisling/RPG_Grid_Brawl
Flee.java
20
import java.io.IOException; import java.math.BigInteger; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Q1 */ @WebServlet("/q1") public class Q1 extends HttpServlet { private static final long serialVersionUID = 1L; private static final String X_VALUE = "6876766832351765396496377534476050002970857483815262918450355869850085167053394672634315391224052153"; BigInteger baseNum; /** * @see HttpServlet#HttpServlet() */ public Q1() { super(); baseNum = new BigInteger(X_VALUE); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String primeNum = request.getParameter("key"); BigInteger num = new BigInteger(primeNum); // To get the result Y value as indicated in writeup BigInteger result = num.divide(baseNum); // Give response to the client response.getWriter().println(result); response.getWriter().println( "SanYingZhanLvBu,9679-6671-5614,5239-8284-2426,3175-8296-3793"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date d = new Date(); response.getWriter().println(df.format(d)); } }
l-wang/Twitter-Analytics-Web-Services
Q1.java
21
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author prate */ import java.io.*; import java.util.*; import javax.swing.JOptionPane; public class ProfessorGUI extends javax.swing.JFrame { int x; int y; ArrayList<ArrayList<String>> ob1 = new ArrayList<ArrayList<String>>(); static Professor professorObj = new Professor(); /** * Creates new form test */ public ProfessorGUI(Professor ob) { professorObj = ob; x = -1; y = -2; for (int i = 0; i < 8; i++) ob1.add(new ArrayList<String>()); changeArrayList(); initComponents(); } private void changeArrayList() { List<String> x=professorObj.getCourses(); for(String i: x) { int sem=i.charAt(8)-'0'; ob1.get(sem-1).add(i.substring(0,5)); } for(ArrayList<String> i:ob1) { String z[]=i.toArray(new String[0]); System.out.println(i.toString()); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); Gender = new javax.swing.JTextField(professorObj.getGender()); Contact = new javax.swing.JTextField(professorObj.getContactNo()); jLabel3 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); Name = new javax.swing.JTextField(professorObj.getName()); DoB = new javax.swing.JFormattedTextField(professorObj.getDob()); jLabel9 = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); Address = new javax.swing.JTextArea(professorObj.getaddress()); jLabel10 = new javax.swing.JLabel(); ID = new javax.swing.JTextField(""+professorObj.getUID()); jLabel2 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); Qualification = new javax.swing.JTextArea(professorObj.getQualification()); jScrollPane4 = new javax.swing.JScrollPane(); AoI = new javax.swing.JTextArea(professorObj.getAreaofInterest()); jLabel4 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); courseList = new javax.swing.JList<>(); jScrollPane5 = new javax.swing.JScrollPane(); SemesterList = new javax.swing.JList<>(); uploadAttendance = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jScrollPane8 = new javax.swing.JScrollPane(); courseList2 = new javax.swing.JList<>(); jScrollPane9 = new javax.swing.JScrollPane(); SemesterList2 = new javax.swing.JList<>(); uploadMarks = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setLocation(600,200); jTabbedPane1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); jTabbedPane1.setFont(new java.awt.Font("Sylfaen", 1, 14)); // NOI18N jLabel1.setText("Name :"); Gender.setEditable(false); Contact.setEditable(false); jLabel3.setText("Date of Birth :"); jLabel5.setText("Contact Number :"); Name.setEditable(false); DoB.setEditable(false); jLabel9.setText("Address :"); Address.setEditable(false); Address.setColumns(15); Address.setRows(2); Address.setWrapStyleWord(true); jScrollPane2.setViewportView(Address); jLabel10.setText("Gender :"); ID.setEditable(false); ID.setToolTipText(""); jLabel2.setText("Qualification :"); jLabel11.setText("Area of Interest :"); Qualification.setEditable(false); Qualification.setColumns(15); Qualification.setRows(2); Qualification.setWrapStyleWord(true); jScrollPane3.setViewportView(Qualification); AoI.setEditable(false); AoI.setColumns(15); AoI.setRows(2); AoI.setWrapStyleWord(true); jScrollPane4.setViewportView(AoI); jLabel4.setText("I.D."); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel9) .addComponent(jLabel11)) .addGap(53, 53, 53) .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 288, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel5) .addComponent(jLabel10) .addComponent(jLabel4)) .addGap(51, 51, 51) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Contact) .addComponent(Name) .addComponent(jScrollPane3) .addComponent(jScrollPane2) .addComponent(DoB) .addComponent(Gender) .addComponent(ID)))) .addGap(60, 60, 60)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(34, 34, 34) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(ID, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(Gender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(DoB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Contact, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel9)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel11) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(42, 42, 42)) ); jTabbedPane1.addTab("Personal Details", jPanel1); jLabel7.setText("Select Semester : "); jLabel8.setText("Select Courses :"); courseList.setDragEnabled(true); jScrollPane1.setViewportView(courseList); SemesterList.setModel(new javax.swing.AbstractListModel<String>() { String[] strings = { "Semester 1", "Semester 2", "Semester 3", "Semester 4", "Semester 5", "Semester 6", "Semester 7", "Semester 8" }; public int getSize() { return strings.length; } public String getElementAt(int i) { return strings[i]; } }); SemesterList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); SemesterList.setToolTipText(""); SemesterList.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); SemesterList.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { SemesterListValueChanged(evt); } }); jScrollPane5.setViewportView(SemesterList); uploadAttendance.setText("Open Sheet"); uploadAttendance.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { uploadAttendanceActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel7) .addGap(64, 64, 64) .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel8) .addGap(74, 74, 74) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(uploadAttendance) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(228, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel7) .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 53, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel8) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(27, 27, 27) .addComponent(uploadAttendance) .addGap(42, 42, 42)) ); jTabbedPane1.addTab("Upload Attendence", jPanel2); jLabel14.setText("Select Semester : "); jLabel15.setText("Select Courses :"); courseList2.setDragEnabled(true); courseList2.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { courseList2ValueChanged(evt); } }); jScrollPane8.setViewportView(courseList2); SemesterList2.setModel(new javax.swing.AbstractListModel<String>() { String[] strings = { "Semester 1", "Semester 2", "Semester 3", "Semester 4", "Semester 5", "Semester 6", "Semester 7", "Semester 8" }; public int getSize() { return strings.length; } public String getElementAt(int i) { return strings[i]; } }); SemesterList2.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); SemesterList2.setToolTipText(""); SemesterList2.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); SemesterList2.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { SemesterList2ValueChanged(evt); } }); jScrollPane9.setViewportView(SemesterList2); uploadMarks.setText("Open Sheet"); uploadMarks.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { uploadMarksActionPerformed(evt); } }); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jLabel14) .addGap(64, 64, 64) .addComponent(jScrollPane9, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jLabel15) .addGap(74, 74, 74) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(uploadMarks) .addComponent(jScrollPane8, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(228, Short.MAX_VALUE)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel14) .addComponent(jScrollPane9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 53, Short.MAX_VALUE) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel15) .addComponent(jScrollPane8, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(28, 28, 28) .addComponent(uploadMarks) .addGap(41, 41, 41)) ); jTabbedPane1.addTab("Upload Marks", jPanel4); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 527, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 493, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void SemesterListValueChanged(javax.swing.event.ListSelectionEvent evt) { ArrayList<String> ob; switch (SemesterList.getSelectedIndex()) { case 0: ob=ob1.get(0); courseList.setModel(new javax.swing.DefaultComboBoxModel<>(ob.toArray(new String[0]))); break; case 1: ob=ob1.get(1); courseList.setModel(new javax.swing.DefaultComboBoxModel<>(ob.toArray(new String[0]))); break; case 2: ob=ob1.get(2); courseList.setModel(new javax.swing.DefaultComboBoxModel<>(ob.toArray(new String[0]))); break; case 3: ob=ob1.get(3); courseList.setModel(new javax.swing.DefaultComboBoxModel<>(ob.toArray(new String[0]))); break; case 4: ob=ob1.get(4); courseList.setModel(new javax.swing.DefaultComboBoxModel<>(ob.toArray(new String[0]))); break; case 5: ob=ob1.get(5); courseList.setModel(new javax.swing.DefaultComboBoxModel<>(ob.toArray(new String[0]))); break; case 6: ob=ob1.get(6); courseList.setModel(new javax.swing.DefaultComboBoxModel<>(ob.toArray(new String[0]))); break; case 7: ob=ob1.get(7); courseList.setModel(new javax.swing.DefaultComboBoxModel<>(ob.toArray(new String[0]))); break; } } private void courseList2ValueChanged(javax.swing.event.ListSelectionEvent evt) { // TODO add your handling code here: } private void SemesterList2ValueChanged(javax.swing.event.ListSelectionEvent evt) { // TODO add your handling code here: } private void uploadAttendanceActionPerformed(java.awt.event.ActionEvent evt) { int sem=SemesterList.getSelectedIndex()+1; String courseCode=courseList.getSelectedValue(); AttendanceWriter ob=new AttendanceWriter(); ob.writeAttendance(sem,courseCode); // TODO add your handling code here: } private void uploadMarksActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ProfessorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ProfessorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ProfessorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ProfessorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ProfessorGUI(professorObj).setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JTextArea Address; private javax.swing.JTextArea AoI; private javax.swing.JTextField Contact; private javax.swing.JFormattedTextField DoB; private javax.swing.JTextField Gender; private javax.swing.JTextField ID; private javax.swing.JTextField Name; private javax.swing.JTextArea Qualification; private javax.swing.JList<String> SemesterList; private javax.swing.JList<String> SemesterList2; private javax.swing.JList<String> courseList; private javax.swing.JList<String> courseList2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JScrollPane jScrollPane5; private javax.swing.JScrollPane jScrollPane8; private javax.swing.JScrollPane jScrollPane9; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JButton uploadAttendance; private javax.swing.JButton uploadMarks; // End of variables declaration }
pAditya198/OOP_Project
j.java
22
/** * Contains all the Constants used in HiJynx */ import java.awt.*; public class c{ public static final int MARGIN = 25; public static final int SMALL = 30; public static final int MED = 50; public static final int LARGE = 70; public static final int HUGE = 200; public static final int UP = 0; public static final int RIGHT = 1; public static final int DOWN = 2; public static final int LEFT = 3; public static final int STATIC = 4; // Edit these: public static final int WIDTH = 1024-15; public static final int HEIGHT = 768-35; public static final int SIZE = MED; public static final int LIFE = 200; public static final int SPEED = 5; // hundredth lengths moved per timer tick public static final int TICK = 25; // milliseconds between ticks public static final int MAXFISH = 100; }
nixhope/MockFish
c.java
23
//Write a program for error detecting code using CRC-CCITT(16-bits) import java.util.Scanner; public class CRC { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("At Sender Side: "); // Input Data Stream System.out.print("Enter message bits: "); String message = sc.nextLine(); System.out.print("Enter generator: "); String generator = sc.nextLine(); int data[] = new int[message.length() + generator.length() - 1]; int divisor[] = new int[generator.length()]; for (int i = 0; i < message.length(); i++) data[i] = Integer.parseInt(message.charAt(i) + ""); for (int i = 0; i < generator.length(); i++) divisor[i] = Integer.parseInt(generator.charAt(i) + ""); // Calculation of CRC for (int i = 0; i < message.length(); i++) { if (data[i] == 1) { for (int j = 0; j < divisor.length; j++) data[i + j] ^= divisor[j]; } } // Append the remainder to the original message for (int i = 0; i < message.length(); i++) data[i] = Integer.parseInt(message.charAt(i) + ""); // Display CRC System.out.print("The checksum code is: "); for (int i = 0; i < data.length; i++) System.out.print(data[i]); System.out.println(); System.out.println("At Receiver Side: "); // Check for input CRC code System.out.print("Enter checksum code: "); message = sc.nextLine(); System.out.print("Enter generator: "); generator = sc.nextLine(); data = new int[message.length() + generator.length() - 1]; divisor = new int[generator.length()]; for (int i = 0; i < message.length(); i++) data[i] = Integer.parseInt(message.charAt(i) + ""); for (int i = 0; i < generator.length(); i++) divisor[i] = Integer.parseInt(generator.charAt(i) + ""); // Calculation of remainder for (int i = 0; i < message.length(); i++) { if (data[i] == 1) for (int j = 0; j < divisor.length; j++) data[i + j] ^= divisor[j]; } // Display validity of data boolean valid = true; for (int i = 0; i < data.length; i++) if (data[i] == 1) { valid = false; break; } if (valid) System.out.println("Data stream is valid"); else System.out.println("Data stream is invalid. CRC error occurred."); } } // fix the generator same at both sender and receiver side // output:- // At Sender Side: // Enter message bits: 100100 // Enter generator: 1101 // The checksum code is: 100100001 // At Receiver Side: // Enter checksum code: 11011 // Enter generator: 1101 // Data stream is invalid. CRC error occurred.
saadhussain01306/computer_net_lab
2.Crc.java
24
/*Write a program to implement random early detection (RED) congestion control algorithm*/ import java.util.Random; import java.util.Scanner; public class RedCongestionControl { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the maximum number of packets:");//number of packets to be sent int maxPackets = scanner.nextInt(); System.out.println("Enter the queue size:");//size of the queue the packets can be stored int queueSize = scanner.nextInt(); System.out.println("Enter the maximum probability:"); double maxProbability = scanner.nextDouble(); System.out.println("Enter the minimum probability:");//used to calculated the drop probabilty (max-min) double minProbability = scanner.nextDouble(); System.out.println("Enter the threshold value:");//the value after which the congestion control comes to action int threshold = scanner.nextInt(); simulateCongestion(maxPackets, queueSize, maxProbability, minProbability, threshold); } private static void simulateCongestion(int maxPackets, int queueSize, double maxProbability, double minProbability, int threshold) { Random rand = new Random(System.currentTimeMillis()); int queueLength = 0; for (int i = 0; i < maxPackets; i++) { double dropProbability = calculateDropProbability(queueLength, queueSize, maxProbability, minProbability, threshold); if (queueLength >= threshold && rand.nextDouble() < dropProbability) { System.out.println("Packet dropped (CONGESTION AVOIDANCE)"); //checking the threshold value and the probabilty to check whether to accept or reject the packet } else { System.out.println("Packet accepted " + (i + 1)); queueLength++; } } } private static double calculateDropProbability(int currentQueueLength, int queueSize, double maxProbability, double minProbability, int threshold) { double slope = (maxProbability - minProbability) / (queueSize - threshold); return minProbability + slope * (currentQueueLength - threshold); } } /* output:- Enter the maximum number of packets: 100 Enter the queue size: 20 Enter the maximum probability: 0.8 Enter the minimum probability: 0.2 Enter the threshold value: 10 Packet accepted 1 Packet accepted 2 Packet accepted 3 Packet accepted 4 Packet accepted 5 Packet accepted 6 Packet accepted 7 Packet accepted 8 Packet accepted 9 Packet accepted 10 Packet accepted 11 Packet accepted 12 Packet accepted 13 Packet accepted 14 Packet accepted 15 Packet accepted 16 Packet accepted 17 Packet dropped (CONGESTION AVOIDANCE) Packet accepted 19 Packet accepted 20 Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet accepted 23 Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet accepted 33 Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet accepted 40 Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet accepted 47 Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Output 2:- Enter the maximum number of packets: 50 Enter the queue size: 10 Enter the maximum probability: 0.6 Enter the minimum probability: 0.4 Enter the threshold value: 5 Packet accepted 1 Packet accepted 2 Packet accepted 3 Packet accepted 4 Packet accepted 5 Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet accepted 9 Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet accepted 13 Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet accepted 17 Packet dropped (CONGESTION AVOIDANCE) Packet accepted 19 Packet accepted 20 Packet accepted 21 Packet accepted 22 Packet accepted 23 Packet accepted 24 Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet accepted 27 Packet dropped (CONGESTION AVOIDANCE) Packet accepted 29 Packet dropped (CONGESTION AVOIDANCE) Packet accepted 31 Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) Packet dropped (CONGESTION AVOIDANCE) */
saadhussain01306/computer_net_lab
8.RED.java
25
import java.io.*; import java.lang.*; class X1 { public static void main(String[]args) throws IOException { BufferedReader venki=new BufferedReader(new InputStreamReader(System.in)); long comp,Cos=0,COs=0,COS=0; double dis; System.out.println("\nEnter the Number of Computers you want to buy : "); comp=Integer.parseInt(venki.readLine()); System.out.println("\nEnter the Number of years you want to deal with : \nNOTE : YOU GET 15% DISCOUNT YOU DEAL FOR MORE THAN 5 YEARS!!"); int year=Integer.parseInt(venki.readLine()); Cos=31500*comp; COs=31000*comp; COS=29000*comp; if(comp<20) { System.out.println("\nAmount to paid : "+Cos); if(year>5) { dis=Cos-(Cos*0.15); System.out.println("\nAmount to Paid with discount : "+dis); } } else if(comp>=20 && comp<=39) { System.out.println("\nAmount to be paid : "+COs); if(year>5) { dis=COs-(COs*0.15); System.out.println("\nAmount to be paid with discount : "+ dis); } } else { System.out.println("\nAmount to be paid : "+ COS); if(year>5) { dis=COS-(COS*0.15); System.out.println("\nAmount to be paid with discount : "+dis); } } } }
flick-23/JAVA-Programs
X1.java
26
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class J here. * * @author (your name) * @version (a version number or a date) */ public class J extends VirtualKeyboard { /** * Act - do whatever the J wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public J() { image.drawString("J", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("J", x, y); wordtoguess.setAlphabetGuessed("J",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
J.java
27
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class Y here. * * @author (your name) * @version (a version number or a date) */ public class Y extends VirtualKeyboard { /** * Act - do whatever the Y wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public Y() { image.drawString("Y", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("Y", x, y); wordtoguess.setAlphabetGuessed("Y",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
Y.java
28
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class X here. * * @author (your name) * @version (a version number or a date) */ public class X extends VirtualKeyboard { /** * Act - do whatever the X wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public X() { image.drawString("X", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("X", x, y); wordtoguess.setAlphabetGuessed("X",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
X.java
29
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class W here. * * @author (your name) * @version (a version number or a date) */ public class W extends VirtualKeyboard { /** * Act - do whatever the W wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public W() { image.drawString("W", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("W", x, y); wordtoguess.setAlphabetGuessed("W",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
W.java
30
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class N here. * * @author (your name) * @version (a version number or a date) */ public class N extends VirtualKeyboard { /** * Act - do whatever the N wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public N() { image.drawString("N", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("N", x, y); wordtoguess.setAlphabetGuessed("N",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
N.java
31
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class Q here. * * @author (your name) * @version (a version number or a date) */ public class Q extends VirtualKeyboard { /** * Act - do whatever the Q wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public Q() { image.drawString("Q", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("Q", x, y); wordtoguess.setAlphabetGuessed("Q",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
Q.java
32
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class E here. * * @author (your name) * @version (a version number or a date) */ public class E extends VirtualKeyboard { /** * Act - do whatever the E wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public E() { image.drawString("E", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /*Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("E", x, y); wordtoguess.setAlphabetGuessed("E", getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
E.java
33
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class F here. * * @author (your name) * @version (a version number or a date) */ public class F extends VirtualKeyboard { /** * Act - do whatever the F wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public F() { image.drawString("F", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("F", x, y); wordtoguess.setAlphabetGuessed("F",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
F.java
34
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class V here. * * @author (your name) * @version (a version number or a date) */ public class V extends VirtualKeyboard { /** * Act - do whatever the V wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public V() { image.drawString("V", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("V", x, y); wordtoguess.setAlphabetGuessed("V",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
V.java
35
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class D here. * * @author (your name) * @version (a version number or a date) */ public class D extends VirtualKeyboard { /** * Act - do whatever the D wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public D() { image.drawString("D", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { //Hangman hangman = (Hangman) getWorld(); //wordtoguess = hangman.getWordToGuess(); WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("D", x, y); wordtoguess.setAlphabetGuessed("D", getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
D.java
36
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class P here. * * @author (your name) * @version (a version number or a date) */ public class P extends VirtualKeyboard { /** * Act - do whatever the P wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public P() { image.drawString("P", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("P", x, y); wordtoguess.setAlphabetGuessed("P",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
P.java
37
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class S here. * * @author (your name) * @version (a version number or a date) */ public class S extends VirtualKeyboard { /** * Act - do whatever the S wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public S() { image.drawString("S", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("S", x, y); wordtoguess.setAlphabetGuessed("S",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
S.java
38
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class U here. * * @author (your name) * @version (a version number or a date) */ public class U extends VirtualKeyboard { /** * Act - do whatever the U wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public U() { image.drawString("U", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("U", x, y); wordtoguess.setAlphabetGuessed("U",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
U.java
39
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class I here. * * @author (your name) * @version (a version number or a date) */ public class I extends VirtualKeyboard { /** * Act - do whatever the I wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public I() { image.drawString("I", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("I", x, y); wordtoguess.setAlphabetGuessed("I",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
I.java
40
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class L here. * * @author (your name) * @version (a version number or a date) */ public class L extends VirtualKeyboard { /** * Act - do whatever the L wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public L() { image.drawString("L", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("L", x, y); wordtoguess.setAlphabetGuessed("L",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
L.java
41
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class H here. * * @author (your name) * @version (a version number or a date) */ public class H extends VirtualKeyboard { /** * Act - do whatever the H wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public H() { image.drawString("H", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("H", x, y); wordtoguess.setAlphabetGuessed("H",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
H.java
42
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class Z here. * * @author (your name) * @version (a version number or a date) */ public class Z extends VirtualKeyboard { /** * Act - do whatever the Z wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public Z() { image.drawString("Z", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("Z", x, y); wordtoguess.setAlphabetGuessed("Z",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
Z.java
43
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class M here. * * @author (your name) * @version (a version number or a date) */ public class M extends VirtualKeyboard { /** * Act - do whatever the M wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public M() { image.drawString("M", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("M", x, y); wordtoguess.setAlphabetGuessed("M",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
M.java
44
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class O here. * * @author (your name) * @version (a version number or a date) */ public class O extends VirtualKeyboard { /** * Act - do whatever the O wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public O() { image.drawString("O", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("O", x, y); wordtoguess.setAlphabetGuessed("O",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
O.java
45
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.*; /** * Write a description of class T here. * * @author (your name) * @version (a version number or a date) */ public class T extends VirtualKeyboard { /** * Act - do whatever the T wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public T() { image.drawString("T", x, y); gi.drawImage(image,0,0); setImage(image); } public void act() { /* Hangman hangman = (Hangman) getWorld(); wordtoguess = hangman.getWordToGuess();*/ WordToGuess wordtoguess = new WordToGuess(); if(Greenfoot.mouseClicked(this) && !isClick) { image.setColor(Color.GREEN); image.drawString("T", x, y); wordtoguess.setAlphabetGuessed("T",getWorld()); isClick = true; } } }
singhalsurbhi07/202-Hangman
T.java
46
package UnionFind; import edu.princeton.cs.algs4.*; // Below is the syntax highlighted version of UnionFind.UF.java from §1.5 Case Study: Union-Find. public class UF { private int[] parent; // parent[i] = parent of i private byte[] rank; // rank[i] = rank of subtree rooted at i (never more than 31) private int count; // number of components public UF(int n) { if (n < 0) throw new IllegalArgumentException(); count = n; parent = new int[n]; rank = new byte[n]; for (int i = 0; i < n; i++) { parent[i] = i; rank[i] = 1; } } public int find(int p) { validate(p); while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } public int count() { return count; } public boolean connected(int p, int q) { return find(p) == find(q); } public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ; else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP; else { parent[rootQ] = rootP; rank[rootP]++; } count--; } // validate that p is a valid index private void validate(int p) { int n = parent.length; if (p < 0 || p >= n) { throw new IllegalArgumentException("index " + p + " is not between 0 and " + (n-1)); } } public static void main(String[] args) { int n = StdIn.readInt(); UF uf = new UF(n); while (!StdIn.isEmpty()) { int p = StdIn.readInt(); int q = StdIn.readInt(); if (uf.connected(p, q)) continue; uf.union(p, q); StdOut.println(p + " " + q); } StdOut.println(uf.count() + " components"); } }
Simply-divine/Union-Find
UF.java
47
/** * 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 middleNode(ListNode head) { ListNode fast = head; ListNode slow = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; } return slow; } }
japygo/LeetCode
0876-middle-of-the-linked-list/0876-middle-of-the-linked-list.java
48
class Solution { public String longestPalindrome(String s) { int left = 0, right = 0, strL = s.length(); String returnStr = ""; for (int i = 0; i < strL; i++) { char charAtI = s.charAt(i); left = i; right = i; // remove dupes for left side character while (left >= 0 && s.charAt(left) == charAtI) { left--; // this number lowest is -1. } // removes dupes for right side character while (right < strL && s.charAt(right) == charAtI) { right++; } // check for further palindrom after accounting for the "dupes" char // from the String. while (left >= 0 && right < strL && s.charAt(left) == s.charAt(right)) { left--; right++; } // update the returnString // left + 1 since the left could enter -1 which the lowest we want here // is 0. if (right - (left + 1) > returnStr.length()) { returnStr = s.substring(left + 1, right); } } return returnStr; } }
kalongn/LeetCode_Solution
5.java
49
class Solution { public String convert(String s, int numRows) { // Get the length of the String input int lenOfS = s.length(); // edge Cases if (lenOfS <= 1 || numRows <= 1) { return s; } // Create a String array String[] strArr = new String[numRows]; // Change to value for every strArr[] from null to an empty String for (int i = 0; i < numRows; i++) { strArr[i] = ""; } // Calculate how large the section is since the relationship is // 3 -> 5, 4 -> 6, 5 ->7 int section = numRows * 2 - 2; // loop over the entire String for (int i = 0; i < lenOfS; i++) { // get the index the item will be added it int index = i % section; // if the index is less then numRows, that mean it is an element insert // vertically. // else if the index is equal or greater then numRwos, that mean it is an // element insert in a reverse diagonal line. Which then we can use the section // and subtract our index from it to get which strArr it will add to. if (index < numRows) { strArr[index] += s.charAt(i); } else { strArr[section - index] += s.charAt(i); } } // concatenate everything into a single string. String returnStr = ""; for (String i : strArr) { returnStr += i; } // return our result. return returnStr; } }
kalongn/LeetCode_Solution
6.java
50
import java.util.*; class p { /* / The Java version of the PL/Vision p package. / Version 2.0 / / Author: Steven Feuerstein / Date: 12/25/98 */ // Delimiter used between data elements. private static String Gdelim = " - "; // Get and Set for delimiter public static void setDelim (String newDelim) { Gdelim = newDelim; } public static String delim () { return Gdelim; } // Overloading for general Object public static void l (Object obj) { System.out.println (obj); } // Overloading for primitive types public static void l (int val) { System.out.println (val); } public static void l (long val) { System.out.println (val); } public static void l (boolean val) { System.out.println (val); } public static void l (float val) { System.out.println (val); } // Combinations of types and objects public static void l (int val1, int val2) { System.out.println (val1 + Gdelim + val2); } public static void l (long val1, long val2) { System.out.println (val1 + Gdelim + val2); } public static void l (boolean val1, boolean val2) { System.out.println (val1 + Gdelim + val2); } public static void l (Date val1, Date val2) { System.out.println (val1 + Gdelim + val2); } public static void l (String val1, String val2) { System.out.println (val1 + Gdelim + val2); } public static void l (String val1, int val2) { System.out.println (val1 + Gdelim + val2); } public static void l (String val1, long val2) { System.out.println (val1 + Gdelim + val2); } public static void l (String val1, Date val2) { System.out.println (val1 + Gdelim + val2); } }
jayvdb/PLSQL-demo-scripts
p.java
51
package gpfinance; import java.util.Random; /** * @date 14-July-2013 * @author Sudheesh Singanamalla */ public class U { /** * Utility class configuration parameters. */ public static final double MAX = 100.0; public static final double MIN = -100.0; public static final boolean debug = true; /** * Set of methods to print the object passed. * p() - prints object with no new line, if debugging * pl() - prints object with a new line, if debugging * m() - prints the object regardless of debug mode */ public static void p(Object o){ if (debug) System.out.print(o); } public static void pl(Object o){ if (debug) System.out.println(o); } public static void m(Object o){ System.out.println(o); } /** * Set of methods to help with random generation of data types. * chance() - 50/50 chance to return true/false * randomVal() - return random double in range [MIN, MAX) */ public static boolean chance(){ return Math.random() < 0.5; } public static double randomVal() { return (MIN + (Math.random() * ((MAX - MIN) + 1.0)) * 0.85); } public static int randomTreeIndex(int size) { return (new Random()).nextInt(size-1) +1; } }
sudheesh001/YahooHackIndia
U.java
52
import java.io.File; // Import the File class import java.io.IOException; // Import the IOException class to handle errors public class CreateFile { public static void main(String[] args) { try { File myObj = new File("filename.txt"); if (myObj.createNewFile()) { System.out.println("File created: " + myObj.getName()); } else { System.out.println("File already exists."); } } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } }
GDSC-MITS/Contribute-To-HacktoberFest
Java Programs/Createfile.java
53
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ class Codechef { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner sc = new Scanner(System.in); int t=sc.nextInt(); while(t>0) { int x = sc.nextInt(); int y = sc.nextInt(); int t1; int r=3*y; t1 = x/r; System.out.println(t1); t--; } } }
asthanegi14/CodeChef-Contest
SONGS
54
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.*; import javax.sound.midi.*; public class F { public static void main(String[] args) throws MidiUnavailableException, InvalidMidiDataException, IOException { //so uhhh i want to read in a midi file //then i need to make those notes light up on the keyboard //simple enough right? //haha jk //oh wait it also needs to wait for the user to press those keys before proceeding //should it also emit the notes before the user plays them? //also need to find music thats within a limited range Vector synthInfos = new Vector(); MidiDevice device = null; MidiDevice keyboard = null; MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo(); Sequencer sequencer; Receiver receiver; Transmitter transmitter = MidiSystem.getTransmitter(); InputStream stream = new FileInputStream(new File("src/minuet.mid")); //new Sequence(Sequence.SMPTE_24, 0, 1); //finds available devices System.out.println(infos.length); for (int i = 0; i < infos.length; i++) { try { device = MidiSystem.getMidiDevice(infos[i]); } catch (MidiUnavailableException e) { // Handle or throw exception... } if (device != null) { synthInfos.add(infos[i]); System.out.println(infos[i].getName()); System.out.println(infos[i].getVendor()); System.out.println(infos[i].getDescription()); System.out.println("number of transmitters " + device.getMaxTransmitters()); System.out.println("number of receivers " + device.getMaxReceivers()); System.out.println(); } } keyboard = MidiSystem.getMidiDevice(infos[7]); sequencer = MidiSystem.getSequencer(); sequencer.setSequence(stream); receiver = keyboard.getReceiver(); sequencer.getTransmitter().setReceiver(receiver); Track track = sequencer.getSequence().getTracks()[0]; int trackSize = track.size(); sequencer.open(); int i = 0; while (i < trackSize) { MidiEvent midiEvent = track.get(i); MidiMessage midiMessage = midiEvent.getMessage(); receiver.send(midiMessage, -1); i++; } sequencer.close(); } }
Texas-Waitlisters/SXSW-2019
F.java
55
import greenfoot.*; /** * Write a description of class Rh here. * * @author (your name) * @version (a version number or a date) */ public class Rh extends Buildings { /** * Act - do whatever the Rh 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. } }
cookiedancer/TCCDirectory
Rh.java
56
package Edureka; public class Fibonacci { public static void main(String[] args) { //initializing the constants int n = 100, t1 = 0, t2 = 1; System.out.print("Upto " + n + ": "); //while loop to calculate fibonacci series upto n numbers while (t1<= n) { System.out.print(t1 + " + "); int sum = t1 + t2; t1 = t2; t2 = sum; } } }
Srutiverma123/Hacktoberfest-2021
Fibonacci.java
57
/*** * Copyright (c) 2011 Diego Maia da Silva www.diegomaia.net/memeannotations * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
bronx/Meme-Annotations
.java
58
package Edureka; import java.util.Scanner; public class Palindrome { static void checkPalindrome(String input) { //Assuming result to be true boolean res = true; int length = input.length(); //dividing the length of the string by 2 and comparing it. for(int i=0; i<= length/2; i++) { if(input.charAt(i) != input.charAt(length-i-1)) { res = false; break; } } System.out.println(input + " is palindrome = "+res); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter your Statement: "); String str = sc.nextLine(); //function call checkPalindrome(str); } }
Srutiverma123/Hacktoberfest-2021
Palindrome.java
59
// Recursive Java program to check if the number is palindrome or not import java.io.*; class Palimdrome { // recursive function that returns the reverse of digits static int rev(int n, int temp) { // base case if (n == 0) return temp; temp = (temp * 10) + (n % 10); return rev(n / 10, temp); } public static void main (String[] args) { int n = 121; int temp = rev(n, 0); if (temp == n) System.out.println("yes"); else System.out.println("no" ); } }
dharmanshu9930/Java
re
60
/*Write a program to find the shortest path between vertices using bellman-ford algorithm.*/ //bellman ford algorithm for shortest distance from a source node to all the remaining nodes import java.util.*; public class BellmanFord { private static int N; private static int[][] graph; public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the number of Vertices : "); N = sc.nextInt(); System.out.println("Enter the Weight Matrix of Graph"); graph = new int[N][N]; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) graph[i][j] = sc.nextInt(); System.out.print("Enter the Source Vertex : "); int source = sc.nextInt(); bellmanFord(source - 1); } public static void bellmanFord(int src) { int[] dist = new int[N]; Arrays.fill(dist, Integer.MAX_VALUE); dist[src] = 0; for (int i = 0; i < N; i++) { for (int u = 0; u < N; u++) { for (int v = 0; v < N; v++) { if (graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) { dist[v] = dist[u] + graph[u][v]; } } } } for (int u = 0; u < N; u++) { for (int v = 0; v < N; v++) { if (graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) { System.out.println("Negative weight cycle detected."); return; } } } printSolution(dist); } public static void printSolution(int[] dist) { System.out.println("Vertex \t Distance from Source"); for (int i = 0; i < N; i++) { System.out.println((i + 1) + "\t\t" + dist[i]); } } } /*output:- Enter the number of Vertices : 5 Enter the Weight Matrix of Graph 0 6 0 7 0 0 0 5 8 -4 0 0 0 0 0 0 0 -3 0 9 2 0 0 0 0 Enter the Source Vertex : 1 Vertex Distance from Source 1 0 2 6 3 4 4 7 5 2 */ /*Enter the number of Vertices : 3 Enter the Weight Matrix of Graph 0 10 5 0 0 -8 0 0 0 Enter the Source Vertex : 1 Vertex Distance from Source 1 0 2 10 3 2 */ /* Enter the number of Vertices : 3 Enter the Weight Matrix of Graph 0 10 0 0 0 20 0 -30 0 Enter the Source Vertex : 1 Negative weight cycle detected. */
saadhussain01306/computer_net_lab
3.bellman_ford.java
61
/*Token Bucket for congestion control*/ /* In this the bucket is filled with constant rate called token_generation_rate untill the bucket is full */ import java.util.Scanner; import java.util.*; public class Token_bucket{ public static void main(String args[]){ Scanner in = new Scanner(System.in); int token_remaining=0;//total tokens in the bucket int token_requested,token_sent; System.out.println("Enter the bucket capacity"); int bucket_capacity=in.nextInt(); System.out.println("Enter the Token generation rate (Rate at which tokens are sent to the bucket)"); int token_gen_rate=in.nextInt(); System.out.println("Enter the number of Cycles the host computer sends the Tokens to the bucket(at constant rate)"); int n=in.nextInt(); System.out.println(String.format("%s\t%s\t%s\t%s", "Time_t", "Tokens Requested", "Tokens Sent", "Tokens Remaining in bucket")); for(int i=0;i<n;i++){ token_requested=token_gen_rate; if(token_requested+token_remaining>bucket_capacity){ token_sent=bucket_capacity-token_remaining; token_remaining=bucket_capacity; } else{ token_sent=token_requested; token_remaining+=token_requested; } System.out.println(String.format("%d\t\t%d\t\t%d\t\t%d", i + 1, token_requested, token_sent, token_remaining)); } } } /*OUTPUT:- Enter the bucket capacity 5 Enter the Token generation rate (Rate at which tokens are sent to the bucket) 2 Enter the number of Cycles the host computer sends the Tokens to the bucket(at constant rate) 6 Time_t Tokens Requested Tokens Sent Tokens Remaining in bucket 1 2 2 2 2 2 2 4 3 2 1 5 4 2 0 5 5 2 0 5 6 2 0 5 */ /*OUTPUT:- Enter the bucket capacity 5 Enter the Token generation rate (Rate at which tokens are sent to the bucket) 2 Enter the number of Cycles the host computer sends the Tokens to the bucket(at constant rate) 6 Time_t Tokens Requested Tokens Sent Tokens Remaining in bucket 1 2 2 2 2 2 2 4 3 2 1 5 4 2 0 5 5 2 0 5 6 2 0 5 */
saadhussain01306/computer_net_lab
9.token_bucket.java
62
/*Write a program for congestion control using leaky bucket algorithm and token bucket algorithm.*/ /*Leaky bucket algorithm*/ import java.util.Scanner; public class Main { public static void main(String args[]) { Scanner in = new Scanner(System.in); int bucket_remaining = 0, sent, received; System.out.println("Enter the bucket capacity"); int bucket_capacity = in.nextInt(); System.out.println("Enter the bucket rate (Rate at which the bucket sends the packets)"); int bucket_rate = in.nextInt(); System.out.println("Enter the number of packets to be sent"); int n = in.nextInt(); int[] buf = new int[30]; // buffer array to store the packets System.out.println("Enter the packets sizes one by one"); for (int i = 0; i < n; i++) { buf[i] = in.nextInt(); } System.out.println(String.format("%s\t\t%s\t\t%s\t%s\t%s","Time_t","P_size","accepted","sent","remaining")); for (int i = 0; i < n; i++) { if (buf[i] != 0) { if (bucket_remaining + buf[i] > bucket_capacity) { received = -1; } else { received = buf[i]; bucket_remaining += buf[i]; } } else { received = 0; } if (bucket_remaining != 0) { if (bucket_remaining < bucket_rate) { sent = bucket_remaining; bucket_remaining = 0; } else { sent = bucket_rate; bucket_remaining = bucket_remaining - bucket_rate; } } else { sent = 0; } if (received == -1) { System.out.println(String.format("%d\t\t%d\t\t%s\t\t%d\t\t%d", i + 1, buf[i], "dropped", sent, bucket_remaining)); } else { System.out.println(String.format("%d\t\t%d\t\t%d\t\t%d\t\t%d", i + 1, buf[i], received, sent, bucket_remaining)); } } } } /*output:- Enter the bucket capacity 6 Enter the bucket rate (Rate at which the bucket sends the packets) 2 Enter the number of packets to be sent 4 Enter the packets sizes one by one 2 3 4 6 Time_t P_size accepted sent remaining 1 2 2 2 0 2 3 3 2 1 3 4 4 2 3 4 6 dropped 2 1 */
saadhussain01306/computer_net_lab
7.leaky_bucket.java
63
package org.ovirt.engine.extensions.aaa.builtin.tools; import static org.ovirt.engine.extensions.aaa.builtin.tools.ManageDomainsArguments.ARG_HELP; import static org.ovirt.engine.extensions.aaa.builtin.tools.ManageDomainsArguments.ARG_LOG4J_CONFIG; import static org.ovirt.engine.extensions.aaa.builtin.tools.ManageDomainsArguments.ARG_LOG_FILE; import static org.ovirt.engine.extensions.aaa.builtin.tools.ManageDomainsArguments.ARG_LOG_LEVEL; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import org.apache.log4j.helpers.LogLog; import org.ovirt.engine.core.utils.log.Log4jUtils; /** * Parses command line arguments, setups logging and executes engine-manage-domains */ public class ManageDomainsExecutor { public static void setupLogging(String log4jConfig, String logFile, String logLevel) { URL cfgFileUrl = null; try { if (log4jConfig == null) { cfgFileUrl = ManageDomainsExecutor.class.getResource("/engine-manage-domains/log4j.xml"); } else { cfgFileUrl = new File(log4jConfig).toURI().toURL(); } Log4jUtils.setupLogging(cfgFileUrl); } catch (MalformedURLException ex) { throw new IllegalArgumentException( String.format("Error loading log4j configuration from '%s': %s", cfgFileUrl, ex.getMessage()), ex); } if (logFile != null) { Log4jUtils.addFileAppender(logFile, logLevel); } } public static void main(String... args) { ManageDomainsArguments mdArgs = null; try { // suppress displaying log4j warnings due to accessing logs when parsing params LogLog.setQuietMode(true); mdArgs = new ManageDomainsArguments(); mdArgs.parse(args); LogLog.setQuietMode(false); setupLogging(mdArgs.get(ARG_LOG4J_CONFIG), mdArgs.get(ARG_LOG_FILE), mdArgs.get(ARG_LOG_LEVEL)); } catch (Throwable t) { System.out.println(t.getMessage()); System.exit(1); } try { if (mdArgs.contains(ARG_HELP)) { mdArgs.printHelp(); System.exit(0); } else { ManageDomains util = new ManageDomains(mdArgs); // it's existence is checked during the parser validation util.init(); util.createConfigurationProvider(); util.runCommand(); } } catch (ManageDomainsResult e) { ManageDomains.exitOnError(e); } System.out.println(ManageDomainsResultEnum.OK.getDetailedMessage()); System.exit(ManageDomainsResultEnum.OK.getExitCode()); } }
Mario-Kart-Felix/project-log4j-3
Manage
64
import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.*; import static java.lang.Math.min; import static java.lang.Math.max; import java.math.BigInteger; public class t { private static InputReader in; private static PrintWriter out; public static void main(String[] args) throws IOException { InputStream inputStream = System.in; in = new InputReader(inputStream); OutputStream outputStream = System.out; out = new PrintWriter(outputStream); processThis("a + b * c + d * e * f + g"); } static void processThis(String strinput) { StringTokenizer tok = new StringTokenizer(strinput," "); System.out.println(tok.toString()); Stack<String> s = new Stack<>(); s.push(""); while (tok.hasMoreTokens()) { String t = tok.nextToken(); if (isOperator(t)) { while (!isHigherOrder(t, s.peek())) System.out.print(s.pop()); s.push(t); } else System.out.print(t); } while (!s.isEmpty()) System.out.print(s.pop()); System.out.println(); } static boolean isOperator(String t) { return t.equals("+") || t.equals("*"); } static boolean isHigherOrder(String x, String y) { if (y.equals("")) return true; if (orderOf(x) > orderOf( y )) return true; return false; } static int orderOf(String op) { if (op.equals("+")) return 1; if (op.equals("*")) return 2; return -99; } // taken from https://codeforces.com/submissions/Petr // together with PrintWriter, these input-output (IO) is much faster than the usual Scanner(System.in) and System.out // please use these classes to avoid your fast algorithm gets Time Limit Exceeded caused by slow input-output (IO) static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
hakimamarullah/Lab-SDA
t.java
65
//{ Driver Code Starts import java.util.*; import java.lang.*; class Node { int data; Node next; Node(int key) { data = key; next = null; } } class Rearr { static Node head; public static void main (String[] args) { Scanner sc = new Scanner(System.in); int t =sc.nextInt(); while(t-- > 0) { int n = sc.nextInt(); int a1 = sc.nextInt(); Node head = new Node(a1); Node temp = head; for(int i = 1; i < n; i++) { int a = sc.nextInt(); temp.next = new Node(a); temp = temp.next; } Solution ob = new Solution(); ob.rearrange(head); printLast(head); System.out.println(); } } public static void printLast(Node node) { while(node != null) { System.out.print(node.data + " "); node = node.next; } } } // } Driver Code Ends /*node class of the linked list class Node { int data; Node next; Node(int key) { data = key; next = null; } }*/ class Solution { public static void rearrange(Node odd) { if (odd == null || odd.next == null) { return; } Node tail = odd; while (tail.next != null) { tail = tail.next; } Node curr = odd; Node nextNode = odd.next; while (curr != tail && nextNode != tail) { curr.next = nextNode.next; nextNode.next = tail.next; tail.next = nextNode; curr = curr.next; nextNode = curr.next; } } }
dhruvabhat24/geek-4-geeks-october
8.java
66
import greenfoot.*; import java.util.List; public class B extends World { private BCounter actCounter; public static final int GROUND_HEIGHT = 360; public static final BVector GRAVITY = new BVector(0.0, 0.2); public static int ballCounter = 0; public static int count = 5; /** * Constructor for objects of class ProjectilePlanet. * */ public B() { super(600, 400, 1); actCounter = new BCounter("verfuegbare Baelle: "); addObject(actCounter, 120, 40); setup(); actCounter.setValue(5); prepare(); } public void act() { if(count> 5){ actCounter.setValue(actCounter.getValue() - 1); count --; } } public void addBall() { ballCounter++; informActors(); } public void subtractBall() { ballCounter--; informActors(); } public void informActors() { List<BKorb> koerbe = getObjects(BKorb.class); List<BAbwurfpunkt> punkte = getObjects(BAbwurfpunkt.class); } /** * Set up */ public void setup() { for (int i = 0; i < 19; i++) { int x = i * 40 + 20; int y = GROUND_HEIGHT + 20; addObject(new BBoden(), x, y); } for (int i = 0; i < 1; i++) { int x = i * 40 + 60; int y = GROUND_HEIGHT - 20 ; addObject(new BKoerper(), x, y); } } /** * Prepare the world for the start of the program. * That is: create the initial objects and add them to the world. */ private void prepare() { BAbwurfpunkt punkt = new BAbwurfpunkt(); addObject(punkt,77,100); BKorb korb1 = new BKorb(); addObject(korb1,280,202); punkt.setLocation(70,333); BRichtungsanzeige richti = new BRichtungsanzeige(); addObject(richti,520,340); BRichtungspfeil pfeili = new BRichtungspfeil(); addObject(pfeili,455,340); } }
THaussler/Projekt
B.java
67
// reverse the given string public class reverse_string { public static void main(String args[]){ String s="MADAM"; String temp=s; int n=s.length(); String ans=""; for(int i=n-1;i>=0;i--){ ans+=s.charAt(i); } System.out.println(ans); if(ans.equals(ans)){ System.out.println("given string is plindrome"); } else{ System.out.println("given string is not plindrome"); } } }
shrinok/Cpp_Lang
b.java
68
// 4 three step 1 create array 2 sort array 3 get the median class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { // super easy to understand // create array int[] merged_arry=new int[nums1.length+nums2.length]; for(int i=0;i<nums1.length;i++){ merged_arry[i]=nums1[i]; } for(int j=0;j<nums2.length;j++){ merged_arry[nums1.length+j]=nums2[j]; } // sort array Arrays.sort(merged_arry); // get the median int t_index=merged_arry.length; if(t_index%2==0){ float result=(merged_arry[t_index/2]+merged_arry[t_index/2-1]); return result/2; } else { return (float)(merged_arry[(t_index-1)/2]); } } }
XuchenSun/leetcode
4.java
69
import java.io.*; import java.util.*; class GFG { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int tc = Integer.parseInt(br.readLine().trim()); while (tc-- > 0) { String roman = br.readLine().trim(); Solution ob = new Solution(); System.out.println(ob.romanToDecimal(roman)); } } } class Solution { // Finds decimal value of a given roman numeral public int romanToDecimal(String str) { // code here int result = 0; int prevValue = 0; // To keep track of the previous symbol's value for (int i = str.length() - 1; i >= 0; i--) { char c = str.charAt(i); int currentValue = romanValue(c); if (currentValue < prevValue) { result -= currentValue; } else { result += currentValue; } prevValue = currentValue; } return result; } private int romanValue(char c) { switch (c) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; default: return 0; } } }
dhruvabhat24/geek-4-geeks-october
6.java
70
//{ Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; class GFG { public static void main(String args[])throws IOException { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); int t = Integer.parseInt(in.readLine().trim()); while(t-- > 0) { String s[] = in.readLine().trim().split(" "); int n = Integer.parseInt(s[0]); int m = Integer.parseInt(s[1]); int a[][] = new int[n][m]; s = in.readLine().trim().split(" "); int ind=0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = Integer.parseInt(s[ind++]); } } Solution ob = new Solution(); ArrayList<Integer> ans = ob.boundaryTraversal(a, n, m); for (int i : ans) { out.print(i + " "); } out.println(); } out.close(); } } // } Driver Code Ends //User function Template for Java class Solution { //Function to return list of integers that form the boundary //traversal of the matrix in a clockwise manner. static ArrayList<Integer> boundaryTraversal(int matrix[][], int n, int m) { ArrayList<Integer> result = new ArrayList<>(); if (n == 1) { for (int j = 0; j < m; j++) { result.add(matrix[0][j]); } } else if (m == 1) { for (int i = 0; i < n; i++) { result.add(matrix[i][0]); } } else { for (int j = 0; j < m; j++) { result.add(matrix[0][j]); } for (int i = 1; i < n; i++) { result.add(matrix[i][m - 1]); } if (n > 1) { for (int j = m - 2; j >= 0; j--) { result.add(matrix[n - 1][j]); } } if (m > 1) { for (int i = n - 2; i >= 1; i--) { result.add(matrix[i][0]); } } } return result; } }
dhruvabhat24/geek-4-geeks-october
3.java
71
package junit.framework; import java.util.List; import org.junit.Ignore; import org.junit.runner.Describable; import org.junit.runner.Description; import org.junit.runner.Request; import org.junit.runner.Runner; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.Filterable; import org.junit.runner.manipulation.Orderer; import org.junit.runner.manipulation.InvalidOrderingException; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runner.manipulation.Orderable; import org.junit.runner.manipulation.Sorter; /** * The JUnit4TestAdapter enables running JUnit-4-style tests using a JUnit-3-style test runner. * * <p> To use it, add the following to a test class: * <pre> public static Test suite() { return new JUnit4TestAdapter(<em>YourJUnit4TestClass</em>.class); } </pre> */ public class JUnit4TestAdapter implements Test, Filterable, Orderable, Describable { private final Class<?> fNewTestClass; private final Runner fRunner; private final JUnit4TestAdapterCache fCache; public JUnit4TestAdapter(Class<?> newTestClass) { this(newTestClass, JUnit4TestAdapterCache.getDefault()); } public JUnit4TestAdapter(final Class<?> newTestClass, JUnit4TestAdapterCache cache) { fCache = cache; fNewTestClass = newTestClass; fRunner = Request.classWithoutSuiteMethod(newTestClass).getRunner(); } public int countTestCases() { return fRunner.testCount(); } public void run(TestResult result) { fRunner.run(fCache.getNotifier(result, this)); } // reflective interface for Eclipse public List<Test> getTests() { return fCache.asTestList(getDescription()); } // reflective interface for Eclipse public Class<?> getTestClass() { return fNewTestClass; } public Description getDescription() { Description description = fRunner.getDescription(); return removeIgnored(description); } private Description removeIgnored(Description description) { if (isIgnored(description)) { return Description.EMPTY; } Description result = description.childlessCopy(); for (Description each : description.getChildren()) { Description child = removeIgnored(each); if (!child.isEmpty()) { result.addChild(child); } } return result; } private boolean isIgnored(Description description_of_the_thing) { return description.getAnnotation(Ignore.class) != null; } @Override public String toString() { return fNewTestClass.getName(); } public void filter(Filter filter) throws NoTestsRemainException { filter.apply(fRunner); } public void sort(Sorter sorter) { sorter.apply(fRunner); } }
bloriot97/codebuff
T.java
72
int R = matrix.length; int C = matrix[0].length; // Create two arrays to keep track of rows and columns to be modified int rowFlag[] = new int[R]; int colFlag[] = new int[C]; // Initialize rowFlag and colFlag arrays for (int i = 0; i < R; i++) { rowFlag[i] = 0; } for (int i = 0; i < C; i++) { colFlag[i] = 0; } // Find the positions of 1s and mark the corresponding rows and columns for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (matrix[i][j] == 1) { rowFlag[i] = 1; colFlag[j] = 1; } } } // Modify the matrix based on rowFlag and colFlag for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (rowFlag[i] == 1 || colFlag[j] == 1) { matrix[i][j] = 1; } } }
dhruvabhat24/geek-4-geeks-october
2.java
73
/* * ============================================================================================ * A1.java : Extends JFrame and contains a panel where shapes move around on the screen. * A4.java * ============================================================================================ */ import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.event.*; import java.util.ArrayList; import javax.swing.tree.*; import javax.swing.JOptionPane.*; public class A4 extends JFrame { private AnimationViewer panel; // panel for bouncing area private JButton fillButton, addNodeButton, removeNodeButton; private JTree tree; JTable table; JComboBox<ShapeType> shapesComboBox; JComboBox<PathType> pathComboBox; JTextField heightTextField, widthTextField, textTextField; JComboBox<ShapeType> InnerShapesComboBox; /** main method for A1 */ public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { new A4(); } }); } /** constructor to initialise components */ public A4() { super("Bouncing Application"); JPanel mainPanel = setUpMainPanel(); add(mainPanel, BorderLayout.CENTER); add(setUpToolsPanel(), BorderLayout.NORTH); addComponentListener( new ComponentAdapter() { // resize the frame and reset all margins for all shapes public void componentResized(ComponentEvent componentEvent) { panel.resetMarginSize(); } }); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = getSize(); setLocation((d.width - frameSize.width) / 2, (d.height - frameSize.height) / 2); pack(); setVisible(true); } public JPanel setUpMainPanel() { JPanel mainPanel = new JPanel(); panel = new AnimationViewer(true); panel.setPreferredSize(new Dimension(Shape.DEFAULT_MARGIN_WIDTH, Shape.DEFAULT_MARGIN_HEIGHT)); JPanel dataPanel = setUpDataPanel(); dataPanel.setPreferredSize(new Dimension(Shape.DEFAULT_MARGIN_WIDTH, Shape.DEFAULT_MARGIN_HEIGHT)); JSplitPane mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, dataPanel, panel); mainSplitPane.setResizeWeight(0.5); mainSplitPane.setOneTouchExpandable(true); mainSplitPane.setContinuousLayout(true); mainPanel.add(mainSplitPane); return mainPanel; } /** Set up the tools panel * @return toolsPanel the Panel */ public JPanel setUpDataPanel() { JPanel tablePanel = new JPanel(new BorderLayout()); panel.setPreferredSize(new Dimension(Shape.DEFAULT_MARGIN_WIDTH, Shape.DEFAULT_MARGIN_HEIGHT/2)); table = new JTable(panel.getShapeModelAdapter()); JScrollPane tableScrollpane = new JScrollPane(table); tableScrollpane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); tablePanel.add(tableScrollpane,BorderLayout.CENTER); JPanel treePanel = new JPanel(new BorderLayout()); treePanel.setPreferredSize(new Dimension(Shape.DEFAULT_MARGIN_WIDTH, Shape.DEFAULT_MARGIN_HEIGHT/2)); tree = new JTree(panel.getShapeModelAdapter()); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.setShowsRootHandles(true); tree.addTreeSelectionListener(new MyTreeSelectionListener()); JScrollPane treeScrollpane = new JScrollPane(tree); treePanel.add(treeScrollpane,BorderLayout.CENTER); JPanel treeButtonsPanel = new JPanel(); addNodeButton = new JButton("Add Node"); addNodeButton.addActionListener( new AddActionListener()); removeNodeButton = new JButton("Remove Node"); removeNodeButton.addActionListener( new RemoveActionListener()); treeButtonsPanel.add(addNodeButton); treeButtonsPanel.add(removeNodeButton); treePanel.add(treeButtonsPanel,BorderLayout.NORTH); JSplitPane dataSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,treePanel,tablePanel); dataSplitPane.setResizeWeight(0.5); dataSplitPane.setOneTouchExpandable(true); dataSplitPane.setContinuousLayout(true); JPanel dataPanel = new JPanel(); dataPanel.add(dataSplitPane); return dataPanel; } //complete inner classes here /** Set up the tools panel * @return toolsPanel the Panel */ public JPanel setUpToolsPanel() { shapesComboBox = new JComboBox<ShapeType>(); shapesComboBox.setModel(new DefaultComboBoxModel<ShapeType>(ShapeType.values())); shapesComboBox.setToolTipText("Set shape"); shapesComboBox.addActionListener( new ShapeActionListener()) ; InnerShapesComboBox = new JComboBox<ShapeType>(); InnerShapesComboBox.setModel(new DefaultComboBoxModel<ShapeType>(new ShapeType[]{ShapeType.RECTANGLE, ShapeType.OVAL})); InnerShapesComboBox.setToolTipText("Set Inner shape"); InnerShapesComboBox.addActionListener( new InnerShapeActionListener()) ; pathComboBox = new JComboBox<PathType>(); pathComboBox.setModel(new DefaultComboBoxModel<PathType>(PathType.values())); pathComboBox.addActionListener( new PathActionListener()); heightTextField = new JTextField(""+ Shape.DEFAULT_HEIGHT); heightTextField.setToolTipText("Set Height"); heightTextField.addActionListener( new HeightActionListener()); //Set up the width TextField widthTextField = new JTextField(""+ Shape.DEFAULT_WIDTH); widthTextField.setToolTipText("Set Width"); widthTextField.addActionListener( new WidthActionListener()); textTextField = new JTextField("" + Shape.DEFAULT_TEXT); textTextField.setToolTipText("Set Text"); textTextField.addActionListener( new TextActionListener()); //Set up the fill colour button fillButton = new JButton("Fill"); fillButton.setToolTipText("Set Fill Color"); fillButton.setForeground(panel.getCurrentColor()); fillButton.addActionListener( new FillActionListener()); JPanel toolsPanel = new JPanel(); toolsPanel.setLayout(new BoxLayout(toolsPanel, BoxLayout.X_AXIS)); toolsPanel.add(new JLabel(" Shape: ", JLabel.RIGHT)); toolsPanel.add(shapesComboBox); toolsPanel.add(new JLabel(" Inner Shape: ", JLabel.RIGHT)); toolsPanel.add(InnerShapesComboBox); toolsPanel.add(new JLabel(" Path: ", JLabel.RIGHT)); toolsPanel.add(pathComboBox); toolsPanel.add(new JLabel(" Width: ", JLabel.RIGHT)); toolsPanel.add(widthTextField); toolsPanel.add( new JLabel(" Height: ", JLabel.RIGHT)); toolsPanel.add(heightTextField); toolsPanel.add( new JLabel(" Text: ", JLabel.RIGHT)); toolsPanel.add(textTextField); toolsPanel.add(fillButton); return toolsPanel; } class ShapeActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { panel.setCurrentShapeType(shapesComboBox.getSelectedIndex()); } } class InnerShapeActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { panel.setCurrentInnerShapeType(InnerShapesComboBox.getSelectedIndex()); } } class PathActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { panel.setCurrentPathType(pathComboBox.getSelectedIndex()); } } class WidthActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { try { int newValue = Integer.parseInt(widthTextField.getText()); if (newValue > 0 && newValue < Shape.DEFAULT_MARGIN_WIDTH/2 ) // if the value is valid, then change the current height panel.setCurrentWidth(newValue); else widthTextField.setText(panel.getCurrentWidth()+""); //undo the changes } catch (Exception ex) { widthTextField.setText(panel.getCurrentWidth()+""); //if the number entered is invalid, reset it } } } class HeightActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { try { int newValue = Integer.parseInt(heightTextField.getText()); if (newValue > 0 && newValue < Shape.DEFAULT_MARGIN_HEIGHT/2 ) // if the value is valid, then change the current height panel.setCurrentHeight(newValue); else heightTextField.setText(panel.getCurrentHeight()+""); //undo the changes } catch (Exception ex) { heightTextField.setText(panel.getCurrentHeight()+""); //if the number entered is invalid, reset it } } } class TextActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { try { String text = textTextField.getText(); panel.setCurrentText(text); } catch (Exception ex) { textTextField.setText(panel.getCurrentText()+""); //if the number entered is invalid, reset it } } } class MyTreeSelectionListener implements TreeSelectionListener{ public void valueChanged(TreeSelectionEvent e){ Object selectedNode = (Object)tree.getLastSelectedPathComponent(); if(selectedNode instanceof NestedShape){ NestedShape ns = (NestedShape)selectedNode; panel.setSelectedNestedShape(ns); } } } class AddActionListener implements ActionListener{ public void actionPerformed(ActionEvent e){ TreePath p = tree.getSelectionPath(); if(p!=null){ Object selectedNode = (Object)tree.getSelectionPath().getLastPathComponent(); if(selectedNode instanceof NestedShape){ NestedShape ns = (NestedShape)selectedNode; panel.addShapeNode(ns); }else{ if(selectedNode instanceof NestedShape==false){ JOptionPane.showMessageDialog(null,"ERROR: Must select a NestedShape node."); }else{ JOptionPane.showMessageDialog(null,"ERROR: No node selected."); } } }else{ JOptionPane.showMessageDialog(null,"ERROR: No node selected."); } } } class RemoveActionListener implements ActionListener{ public void actionPerformed(ActionEvent e){ TreePath p = tree.getSelectionPath(); if(p!=null){ Shape selectedNode = (Shape)tree.getSelectionPath().getLastPathComponent(); if(panel.isRoot(selectedNode)){ JOptionPane.showMessageDialog(null,"ERROR: Must not remove the root."); }else{ Shape ns = (Shape)selectedNode; panel.removeShapeNode(ns); } }else{ JOptionPane.showMessageDialog(null,"ERROR: No node selected."); } } } class FillActionListener implements ActionListener { public void actionPerformed( ActionEvent e) { Color newColor = JColorChooser.showDialog(panel, "Fill Color", panel.getCurrentColor()); if ( newColor != null) { fillButton.setForeground(newColor); panel.setCurrentColor(newColor); } } } }
hwen554/The-Bouncing-Program-
A4.java
74
public class EV extends Car { private int numMotors; public EV() { super(); } public EV(String name, String model, int age, int numMotors) { super(name, model, age); this.numMotors = numMotors; } @Override // optional public int getRemainingLife() { return 10*numMotors - this.getAge(); // made up calculation } public int getMotors() { return numMotors; } // talk about how the private instance vars from Car aren't inherited, need to use getAge() // need to add constructors }
jerrywzhang/IntroToCS
EV.java
75
//{ Driver Code Starts //Initial Template for Java import java.util.LinkedList; import java.util.Queue; import java.io.*; import java.util.*; class Node{ int data; Node left; Node right; Node(int data){ this.data = data; left=null; right=null; } } class GfG { static Node buildTree(String str){ if(str.length()==0 || str.charAt(0)=='N'){ return null; } String ip[] = str.split(" "); // Create the root of the tree Node root = new Node(Integer.parseInt(ip[0])); // Push the root to the queue Queue<Node> queue = new LinkedList<>(); queue.add(root); // Starting from the second element int i = 1; while(queue.size()>0 && i < ip.length) { // Get and remove the front of the queue Node currNode = queue.peek(); queue.remove(); // Get the current node's value from the string String currVal = ip[i]; // If the left child is not null if(!currVal.equals("N")) { // Create the left child for the current node currNode.left = new Node(Integer.parseInt(currVal)); // Push it to the queue queue.add(currNode.left); } // For the right child i++; if(i >= ip.length) break; currVal = ip[i]; // If the right child is not null if(!currVal.equals("N")) { // Create the right child for the current node currNode.right = new Node(Integer.parseInt(currVal)); // Push it to the queue queue.add(currNode.right); } i++; } return root; } static void printInorder(Node root) { if(root == null) return; printInorder(root.left); System.out.print(root.data+" "); printInorder(root.right); } static void displayCList(Node head) { Node itr = head; do { System.out.print(itr.data + " "); itr = itr.right; } while (head!=itr); System.out.println(); itr=itr.left; head = itr; do{ System.out.print(itr.data + " "); itr=itr.left; }while(head!=itr); System.out.println(); } public static void main (String[] args) throws IOException { BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); while(t-- > 0){ String s= br.readLine(); Node root = buildTree(s); Solution boj = new Solution(); Node head = boj.bTreeToClist(root); displayCList(head); } } } // } Driver Code Ends //User function Template for Java //User function Template for Java /* Node defined as class Node{ int data; Node left,right; Node(int d){ data=d; left=right=null; } } */ class Solution { Node head; Node prev; void dfs(Node root) { if(root!=null) { dfs(root.left); if(prev!=null) { prev.right=root; root.left=prev; } else head=root; prev=root; dfs(root.right); } } //Function to convert binary tree into circular doubly linked list. Node bTreeToClist(Node root) { prev=null; head=null; dfs(root); head.left=prev; prev.right=head; return head; } }
dhruvabhat24/Geeks-4-Geeks_November
17.java
76
/****************************************************************************** * Compilation: javac UF.java * Execution: java UF < input.txt * Dependencies: StdIn.java StdOut.java * Data files: http://algs4.cs.princeton.edu/15uf/tinyUF.txt * http://algs4.cs.princeton.edu/15uf/mediumUF.txt * http://algs4.cs.princeton.edu/15uf/largeUF.txt * * Weighted quick-union by rank with path compression by halving. * * % java UF < tinyUF.txt * 4 3 * 3 8 * 6 5 * 9 4 * 2 1 * 5 0 * 7 2 * 6 1 * 2 components * ******************************************************************************/ /** * The {@code UF} class represents a <em>union–find data type</em> * (also known as the <em>disjoint-sets data type</em>). * It supports the <em>union</em> and <em>find</em> operations, * along with a <em>connected</em> operation for determining whether * two sites are in the same component and a <em>count</em> operation that * returns the total number of components. * <p> * The union–find data type models connectivity among a set of <em>n</em> * sites, named 0 through <em>n</em>–1. * The <em>is-connected-to</em> relation must be an * <em>equivalence relation</em>: * <ul> * <li> <em>Reflexive</em>: <em>p</em> is connected to <em>p</em>. * <li> <em>Symmetric</em>: If <em>p</em> is connected to <em>q</em>, * then <em>q</em> is connected to <em>p</em>. * <li> <em>Transitive</em>: If <em>p</em> is connected to <em>q</em> * and <em>q</em> is connected to <em>r</em>, then * <em>p</em> is connected to <em>r</em>. * </ul> * <p> * An equivalence relation partitions the sites into * <em>equivalence classes</em> (or <em>components</em>). In this case, * two sites are in the same component if and only if they are connected. * Both sites and components are identified with integers between 0 and * <em>n</em>–1. * Initially, there are <em>n</em> components, with each site in its * own component. The <em>component identifier</em> of a component * (also known as the <em>root</em>, <em>canonical element</em>, <em>leader</em>, * or <em>set representative</em>) is one of the sites in the component: * two sites have the same component identifier if and only if they are * in the same component. * <ul> * <li><em>union</em>(<em>p</em>, <em>q</em>) adds a * connection between the two sites <em>p</em> and <em>q</em>. * If <em>p</em> and <em>q</em> are in different components, * then it replaces * these two components with a new component that is the union of * the two. * <li><em>find</em>(<em>p</em>) returns the component * identifier of the component containing <em>p</em>. * <li><em>connected</em>(<em>p</em>, <em>q</em>) * returns true if both <em>p</em> and <em>q</em> * are in the same component, and false otherwise. * <li><em>count</em>() returns the number of components. * </ul> * <p> * The component identifier of a component can change * only when the component itself changes during a call to * <em>union</em>—it cannot change during a call * to <em>find</em>, <em>connected</em>, or <em>count</em>. * <p> * This implementation uses weighted quick union by rank with path compression * by halving. * Initializing a data structure with <em>n</em> sites takes linear time. * Afterwards, the <em>union</em>, <em>find</em>, and <em>connected</em> * operations take logarithmic time (in the worst case) and the * <em>count</em> operation takes constant time. * Moreover, the amortized time per <em>union</em>, <em>find</em>, * and <em>connected</em> operation has inverse Ackermann complexity. * For alternate implementations of the same API, see * {@link QuickUnionUF}, {@link QuickFindUF}, and {@link WeightedQuickUnionUF}. * * <p> * For additional documentation, see <a href="http://algs4.cs.princeton.edu/15uf">Section 1.5</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class UF { private int[] parent; // parent[i] = parent of i private byte[] rank; // rank[i] = rank of subtree rooted at i (never more than 31) private int count; // number of components /** * Initializes an empty union–find data structure with {@code n} sites * {@code 0} through {@code n-1}. Each site is initially in its own * component. * * @param n the number of sites * @throws IllegalArgumentException if {@code n < 0} */ public UF(int n) { if (n < 0) throw new IllegalArgumentException(); count = n; parent = new int[n]; rank = new byte[n]; for (int i = 0; i < n; i++) { parent[i] = i; rank[i] = 0; } } /** * Returns the component identifier for the component containing site {@code p}. * * @param p the integer representing one site * @return the component identifier for the component containing site {@code p} * @throws IndexOutOfBoundsException unless {@code 0 <= p < n} */ public int find(int p) { validate(p); while (p != parent[p]) { parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } return p; } /** * Returns the number of components. * * @return the number of components (between {@code 1} and {@code n}) */ public int count() { return count; } /** * Returns true if the the two sites are in the same component. * * @param p the integer representing one site * @param q the integer representing the other site * @return {@code true} if the two sites {@code p} and {@code q} are in the same component; * {@code false} otherwise * @throws IndexOutOfBoundsException unless * both {@code 0 <= p < n} and {@code 0 <= q < n} */ public boolean connected(int p, int q) { return find(p) == find(q); } /** * Merges the component containing site {@code p} with the * the component containing site {@code q}. * * @param p the integer representing one site * @param q the integer representing the other site * @throws IndexOutOfBoundsException unless * both {@code 0 <= p < n} and {@code 0 <= q < n} */ public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make root of smaller rank point to root of larger rank if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ; else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP; else { parent[rootQ] = rootP; rank[rootP]++; } count--; } // validate that p is a valid index private void validate(int p) { int n = parent.length; if (p < 0 || p >= n) { throw new IndexOutOfBoundsException("index " + p + " is not between 0 and " + (n-1)); } } /** * Reads in a an integer {@code n} and a sequence of pairs of integers * (between {@code 0} and {@code n-1}) from standard input, where each integer * in the pair represents some site; * if the sites are in different components, merge the two components * and print the pair to standard output. * * @param args the command-line arguments */ public static void main(String[] args) { int n = StdIn.readInt(); UF uf = new UF(n); while (!StdIn.isEmpty()) { int p = StdIn.readInt(); int q = StdIn.readInt(); if (uf.connected(p, q)) continue; uf.union(p, q); StdOut.println(p + " " + q); } StdOut.println(uf.count() + " components"); } }
drawar/princeton-algorithms
UF.java
77
import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class pr extends JFrame { static int c = 1; private JPanel contentPane; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { pr frame = new pr(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public pr() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(183, 11, 216, 239); contentPane.add(scrollPane); JTextArea textArea = new JTextArea(); scrollPane.setViewportView(textArea); JButton btnNewButton = new JButton("Click ME!!"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { int temp=0,temp2=0; temp2=SimpleLR.in[c]; for(int i=0;i<temp2 ;i++){ if(SimpleLR.il[c][i]!=null && temp2>i && SimpleLR.il[c][0]!=null) {temp=1; textArea.append(SimpleLR.il[c][i]+"->"+SimpleLR.ir[c][i]+"\n"); } } if(temp==0){ textArea.append("SORRY NO PRODUCTION!!! "); } } }); btnNewButton.setBounds(40, 41, 100, 50); contentPane.add(btnNewButton); JButton btnNewButton_1 = new JButton("Back**"); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { pr newfirst=new pr(); newfirst.dispose(); it newset=new it(); newset.setVisible(true); } }); btnNewButton_1.setBounds(40, 161, 89, 41); contentPane.add(btnNewButton_1); } /*public pr(int U) { c = U; initComponents(); }*/ }
harshad16/Slr-parser-using-Java
pr.java
78
//{ Driver Code Starts //Initial Template for Java import java.util.LinkedList; import java.util.Queue; import java.io.*; import java.util.*; import java.math.*; class Node{ int data; Node left, right; Node(int data){ this.data = data; left=null; right=null; } } // } Driver Code Ends //User function Template for Java class Solution { private static HashSet<Integer> hset; //used to store values from bst private static ArrayList<Integer> list;//it store coommon values private static boolean traverse; public static ArrayList<Integer> findCommon(Node root1,Node root2) { //code here hset = new HashSet<>(); //initialize the hashset list = new ArrayList<>();//initialize the arraylist traverse = false ; inorder(root1);//traverse the first bst traverse = true; inorder(root2); // traverse the second bst return list;//return the list of common values } //helper function to perform an in-order traversa; of bst private static void inorder(Node root){ if(root == null){ return; } inorder(root.left); if(!traverse){ hset.add(root.data); //add values to the hashset from first bst }else{ if(hset.contains(root.data)){ list.add(root.data); //if value is in hashset ,it's a coommon value ,so add it to the list } } inorder(root.right); return; } } //{ Driver Code Starts. class GFG { static Node buildTree(String str) { // Corner Case if(str.length() == 0 || str.equals('N')) return null; String[] s = str.split(" "); Node root = new Node(Integer.parseInt(s[0])); Queue <Node> q = new LinkedList<Node>(); q.add(root); // Starting from the second element int i = 1; while(!q.isEmpty() && i < s.length) { // Get and remove the front of the queue Node currNode = q.remove(); // Get the current node's value from the string String currVal = s[i]; // If the left child is not null if(!currVal.equals("N")) { // Create the left child for the current node currNode.left = new Node(Integer.parseInt(currVal)); // Push it to the queue q.add(currNode.left); } // For the right child i++; if(i >= s.length) break; currVal = s[i]; // If the right child is not null if(!currVal.equals("N")) { // Create the right child for the current node currNode.right = new Node(Integer.parseInt(currVal)); // Push it to the queue q.add(currNode.right); } i++; } return root; } public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine().trim()); while(t>0) { String s = br.readLine(); Node root1 = buildTree(s); s = br.readLine(); Node root2 = buildTree(s); Solution g = new Solution(); ArrayList<Integer> res = new ArrayList<Integer>(); res = g.findCommon(root1,root2); for(int i = 0;i<res.size();i++) System.out.print(res.get(i) + " "); System.out.println(); t--; } } } // } Driver Code Ends
dhruvabhat24/geek-4-geeks-october
15.java
79
//{ Driver Code Starts //Initial Template for Java import java.util.LinkedList; import java.util.Queue; import java.io.*; import java.util.*; class Node{ int data; Node left; Node right; Node(int data){ this.data = data; left=null; right=null; } } class Tree { static Node buildTree(String str){ if(str.length()==0 || str.charAt(0)=='N'){ return null; } String ip[] = str.split(" "); // Create the root of the tree Node root = new Node(Integer.parseInt(ip[0])); // Push the root to the queue Queue<Node> queue = new LinkedList<>(); queue.add(root); // Starting from the second element int i = 1; while(queue.size()>0 && i < ip.length) { // Get and remove the front of the queue Node currNode = queue.peek(); queue.remove(); // Get the current node's value from the string String currVal = ip[i]; // If the left child is not null if(!currVal.equals("N")) { // Create the left child for the current node currNode.left = new Node(Integer.parseInt(currVal)); // Push it to the queue queue.add(currNode.left); } // For the right child i++; if(i >= ip.length) break; currVal = ip[i]; // If the right child is not null if(!currVal.equals("N")) { // Create the right child for the current node currNode.right = new Node(Integer.parseInt(currVal)); // Push it to the queue queue.add(currNode.right); } i++; } return root; } static void printInorder(Node root) { if(root == null) return; printInorder(root.left); System.out.print(root.data+" "); printInorder(root.right); } public static void main (String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); while(t > 0){ String s = br.readLine(); Node root = buildTree(s); GfG g = new GfG(); if(g.isSymmetric(root) == true) System.out.println("True"); else System.out.println("False"); t--; } } } // } Driver Code Ends /* class of the node of the tree is as class Node{ int data; Node left; Node right; Node(int data){ this.data = data; left=null; right=null; } } */ // complete this function // return true/false if the is Symmetric or not class GfG { private static boolean mirror(Node l, Node r) { if(l==null ^ r==null) { return false; } else { if(l==null) { return true; } else { if(l.data == r.data) { return mirror(l.left, r.right) && mirror(l.right, r.left); } else { return false; } } } } // return true/false denoting whether the tree is Symmetric or not public static boolean isSymmetric(Node root) { if(root==null) { return true; } return mirror(root.left, root.right); } }
dhruvabhat24/Geeks-4-Geeks_November
22.java
80
//{ Driver Code Starts //Initial Template for Java import java.io.*; import java.util.*; // } Driver Code Ends //User function Template for Java class CheckBit { // Function to check if Kth bit is set or not. static boolean checkKthBit(int n, int k) { // Your code here if (k < 0 || k >= 32) { return false; } String binaryString = Integer.toBinaryString(n); int bitPosition = binaryString.length() - 1 - k; if (bitPosition < 0) { return false; } return binaryString.charAt(bitPosition) == '1'; } } //{ Driver Code Starts. class GFG { static int n; static int k; // Driver Code public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); //Inputting the testcases while(t>0) //While testcases exist { n = Integer.parseInt(br.readLine()); //Input N k = Integer.parseInt(br.readLine()); // Input K CheckBit obj = new CheckBit(); if(obj.checkKthBit(n, k)) System.out.println("Yes"); //If true, print Yes else System.out.println("No"); // Else print No t--; } } } // } Driver Code Ends
dhruvabhat24/geek-4-geeks-october
30.java
81
//{ Driver Code Starts //Initial Template for Java //Contributed by Sudarshan Sharma import java.util.LinkedList; import java.util.Queue; import java.io.*; import java.util.*; class Node{ int data; Node left; Node right; Node(int data){ this.data = data; left=null; right=null; } } class GfG { static Node buildTree(String str){ if(str.length()==0 || str.charAt(0)=='N'){ return null; } String ip[] = str.split(" "); // Create the root of the tree Node root = new Node(Integer.parseInt(ip[0])); // Push the root to the queue Queue<Node> queue = new LinkedList<>(); queue.add(root); // Starting from the second element int i = 1; while(queue.size()>0 && i < ip.length) { // Get and remove the front of the queue Node currNode = queue.peek(); queue.remove(); // Get the current node's value from the string String currVal = ip[i]; // If the left child is not null if(!currVal.equals("N")) { // Create the left child for the current node currNode.left = new Node(Integer.parseInt(currVal)); // Push it to the queue queue.add(currNode.left); } // For the right child i++; if(i >= ip.length) break; currVal = ip[i]; // If the right child is not null if(!currVal.equals("N")) { // Create the right child for the current node currNode.right = new Node(Integer.parseInt(currVal)); // Push it to the queue queue.add(currNode.right); } i++; } return root; } static void printInorder(Node root) { if(root == null) return; printInorder(root.left); System.out.print(root.data+" "); printInorder(root.right); } public static void main (String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); while(t-- > 0){ String s1 = br.readLine(); String s2 = br.readLine(); Node root1 = buildTree(s1); Node root2 = buildTree(s2); Solution g = new Solution(); //System.out.println(g.isIdentical(root,roott)); boolean b = g.isIdentical(root1,root2); if(b==true) System.out.println("Yes"); else System.out.println("No"); } } } // } Driver Code Ends //User function Template for Java /* class Node{ int data; Node left,right; Node(int d){ data=d; left=right=null; } }*/ class Solution { //Function to check if two trees are identical. boolean isIdentical(Node root1, Node root2) { // Code Here if((root1 == null && root2 != null ) || (root1 != null && root2 == null)) { return false; } if(root1 == null && root2 == null) { return true; } if(root1.data != root2.data) { return false; } return isIdentical(root1.left, root2.left) && isIdentical(root1.right, root2.right); } }
dhruvabhat24/Geeks-4-Geeks_November
21.java
82
public class p { public static void main(String[] args) { System.out.println("Hello World");// println is used to end the line System.out.print("aryan is the best "); }}
vampire20045/java
p.java
83
import java.util.*; public class c { public static void main(String[] args) { System.out.println("please enter your choice"); Scanner sc = new Scanner(System.in); int b = sc.nextInt(); switch (b) { case 1: System.out.println("first button is pressed "); break; case 2: System.out.println("third button is pressed "); break; case 3: System.out.println("second button is pressed "); break; default: System.out.println("please enter the correct the choice "); } } }
vampire20045/java
c.java
84
/** * Write a description of class J here. * * @author (your name) * @version (a version number or a date) */ public class J { // instance variables - replace the example below with your own private int x; /** * Constructor for objects of class J */ public J() { // initialise instance variables x = 0; } /** * An example of a method - replace this comment with your own * * @param y a sample parameter for a method * @return the sum of x and y */ public int sampleMethod(int y) { // put your code here return x + y; } }
boisgera/bluej-test
J.java
85
//reverse a given number package com.tgt.igniteplus; import java.util.Scanner; public class Q9 { static float reverseDig(float num) { float rev_num = 0; while(num > 0) { rev_num = rev_num * 10 + num % 10; num = num / 10; } return rev_num; } // Driver code public static void main (String[] args) { System.out.println("Enter the number\n"); Scanner in=new Scanner(System.in); float num=in.nextFloat(); System.out.println("Reverse of number is " + reverseDig(num)); } }
IgnitePlus2020/Prakruthi_Assignment1
Q9.java
86
//Largest and second largest of the lot package com.tgt.igniteplus; import java.util.Scanner; public class Q7 { public static void main(String[] args) { int a,b,c; System.out.print("Enter three numbers\n"); Scanner in=new Scanner(System.in); a=in.nextInt(); b=in.nextInt(); c=in.nextInt(); if(a>b && a>c) { System.out.println("Largest= "+a); if(b<c)System.out.print("Second largest= "+c); else System.out.print("Second largest:"+b); } else if(b>a && b>c) { System.out.println("Largest= "+b); if(a<c)System.out.print("Second largest= "+c); else System.out.print("Second largest= "+a); } else { System.out.println("Largest:" + c); if (b < a) System.out.print("Second largest= " + a); else System.out.print("Second largest= " + b); } } }
IgnitePlus2020/Prakruthi_Assignment1
Q7.java
87
import java.io.*; import java.util.*; /** * @author Wah Loon Keng */ /** This class compiles and run the project */ public class P3 { // private Builder builder; private PrintWriter printer, printerA, printerT; /** The main method, calls initialize() and run() */ public static void main(String[] args) throws Exception{ P3 sheep = new P3(); sheep.initialize(); long startTime = System.nanoTime(); // sheep.runAndTime(); sheep.runAndAnalyze(); long stopTime = System.nanoTime(); double time = (double)(stopTime - startTime) /(1000000000.); System.out.println("Time taken " + time); } /** * Initialize the project and prepare I/O */ public void initialize() throws Exception { String outFile = "mapping.txt"; String outFileA = "analysis.txt"; // String outFileT = "timing.txt"; printer = new PrintWriter(new FileWriter(outFile)); printerA = new PrintWriter(new FileWriter(outFileA)); // printerT = new PrintWriter(new FileWriter(outFileT)); } /** * Run and write the formatted project output to "mapping.txt" * Analyze performance and print result to "analysis.txt" */ public void runAndAnalyze() throws Exception { Builder builder = new Builder(); // do for each given data file for(int file = 1; file < 28; file++) { System.out.println("Batch: " + file); printer.println("Batch: " + file); // build NNGraph and analyze builder.build(file); // index data printerA.print(file + " "); analyze(builder); // print the paths printPaths(builder); } // close printerA after all analysis printer.close(); printerA.close(); } /** * Run and write the formatted project output to "mapping.txt" * Print runtime to "timing.txt" */ public void runAndTime() throws Exception { Builder builder = new Builder(); // do for each given data file for(int file = 1; file < 28; file++) { System.out.println("Batch: " + file); printer.println("Batch: " + file); // print time to build and run builder.buildGraph(file); long startTime = System.nanoTime(); // builder.build(file); builder.runNN(); long stopTime = System.nanoTime(); builder.formatOutput(); double time = stopTime - startTime; printerT.println(file + " " + time); // print all paths for each batch printPaths(builder); } // close printers after all batches are done printer.close(); printerT.close(); } /** * Method to run analysis on each batch of data (paths): * <minSize> <maxSize> <avgSize> <minDist> <maxDist> <avgDist> * where Size is the number of stations the path crosses, and Dist is the distance of the path * @param builder Of an NNGraph. */ protected void analyze(Builder builder) { // variables for calculations int minSize, maxSize, minDist, maxDist, totSize, totDist, count; minSize = minDist = Integer.MAX_VALUE; maxSize = maxDist = totSize = totDist = count = 0; double avgSize = 0, avgDist = 0; for (ArrayList<Integer> tmp : builder.reducedPaths) { int size = tmp.size()-1; int dist = tmp.get(size); // update min max if (size < minSize) minSize = size; if (size > maxSize) maxSize = size; if (dist < minDist) minDist = dist; if (dist > maxDist) maxDist = dist; // update tot and count for avg count++; totSize += size; totDist += dist; } // finally, calculate averages avgSize = (double) totSize/count; avgDist = (double) totDist/count; // then print all 6 numbers printerA.println(minSize + " " + maxSize + " " + avgSize + " " + minDist + " " + maxDist + " " + avgDist); } /** * Print the paths as formatted for project requirement: * <depot> <station> <station> ... <station> <path distance> * @param builder Of an NNGraph. */ protected void printPaths(Builder builder) { for (ArrayList<Integer> tmp : builder.reducedPaths) { for (int i : tmp) { // print key of each vertex System.out.print(i + " "); printer.print(i + " "); } System.out.print("\n"); printer.print("\n"); } System.out.print("\n"); printer.print("\n"); } }
kengz/CS150-graph-optimization
P3.java
88
import java.applet.*; import java.awt.*; import java.awt.event.*; /** Applet to show the Kronig-Penney model for periodic potential. */ public class KP extends BaseApplet2 { public void init() { super.init(); double P = 3/2; double maxX = 4; boolean fold = false, neg = false, free = false; this.negative = neg; eqn = new KronigPenney(Math.PI*P); cache = new SolnCache(eqn); plotter = new Plotter(cache); plotter.setViewAndRange(negative?-maxX:0,maxX); plotter.setInterpolated(false); plotter.setLabels("ka/pi","Energy"); freePlotter = new Plotter(new FreeElectron()); freePlotter.setInterpolated(true); freePlotter.setAxes(false); freePlotter.setScalesEnabled(false,false); massPlotter = new Plotter(new EffectiveMass(cache)); massPlotter.setLabels("ka/pi","Eff.\nmass"); massPlotter.bottomMargin = 0; setLayout(new GridLayout(3,3)); pField = addField("Potential strength/pi",P); freeBox = addCheckbox("Free electron",free); maxXField = addField("Max ka/pi",maxX); negBox = addCheckbox("Include negative",neg); add(statusLabel); add(new Label()); foldBox = addCheckbox("Fold",fold); } /** Reads in (and validates) input from the text fields. @throws IllegalArgumentException if any input fields are invalid */ public void updateInput() { double p = Math.PI*getDouble(pField); double maxX = getDouble(maxXField); validateInput(p,maxX); negative = negBox.getState(); plotter.setRangeX(negative?-maxX:0,maxX); setFolded(foldBox.getState()); ((KronigPenney) eqn).p = p; } /** Performs the validation for {@link #updateInput() updateInput()}. */ public void validateInput(double p, double maxX) { if(p<0) throw new IllegalArgumentException("Need pot. str. >= 0"); if(maxX<=0) throw new IllegalArgumentException("Need max ka > 0"); if(!safetyLimit) return; if(p/Math.PI>4) throw new IllegalArgumentException("Need pot. str. <= 4"); if(maxX>40) throw new IllegalArgumentException("Need max ka <= 40"); } public void start() { super.start(); } public void stop() { super.stop(); } public void actionPerformed(ActionEvent ae) { try{ updateInput(); }catch(IllegalArgumentException e) { String message = e.getMessage(); if(e instanceof NumberFormatException) message = "Bad number: "+message; statusLabel.setText(message); return; } statusLabel.setText(""); refresh(); } protected void updateSolution(int w, int h) { //int virtualWidth = ; int stepsPerPixel = 1; if(folded) w *= stepsPerPixel*plotter.rangeX/plotter.viewRange; freePlotter.copyScale(plotter); freePlotter.updateSolution(w); freePlotter.scaleToFit(0,w); freePlotter.setRangeY(0,freePlotter.maxY); plotter.copyScale(freePlotter); plotter.updateSolution(w); massPlotter.copyScale(freePlotter); massPlotter.updateSolution(w); //massPlotter.scaleToFit(0,w); //massPlotter.setRangeY(-5,5); massPlotter.setRangeY(-0.05,1.05); } /** Used to set whether or not the <i>x</i>-axis is &quot;folded&quot; onto itself. */ public void setFolded(boolean b) { // Careful... if(this.folded = b) plotter.setView(negative?-1:0, 1); else plotter.setView(plotter.minX,plotter.maxX); freePlotter.copyScale(plotter); } public void doPaint(Graphics g) { FontMetrics fm = g.getFontMetrics(); int hSpace = plotter.getSpaceX(fm); int vSpace = plotter.getSpaceY(fm); cache.invalidate(); plotter.setFold(folded,1,negative); freePlotter.setFold(folded,1,negative); massPlotter.setFold(folded,1,negative); int w = getSize().width/2; int h = getGraphHeight(); updateSolution(w-hSpace,h-vSpace); g.setColor(ENERGY_COL); plotter.paint(g,w,h); if(freeBox.getState()) { g.setColor(FREE_COL); g.translate(hSpace,0); freePlotter.paint(g,w-hSpace,h-vSpace); g.translate(-hSpace,0); } g.translate(w,0); g.setColor(Color.black); massPlotter.paint(g,w,h); g.translate(-w,0); } protected TextField pField, maxXField; protected Checkbox foldBox, negBox, freeBox; /** <code>true</code> if the <i>x</i>-axis is folded, else <code>false</code> */ protected boolean folded = false; /** <code>true</code> if the <i>x</i>-axis includes negative values, else <code>false</code> */ protected boolean negative=true; /** The Kronig-Penny model */ protected Solvable eqn; /** Stores solution, so that folding/unfolding does not require recalculation */ protected SolnCache cache; protected Plotter plotter, freePlotter, massPlotter; protected static Color AXES_COL = Color.blue, ENERGY_COL = Color.black, FREE_COL = Color.red; }
thomascherickal/Java-Code
KP.java
89
import java.util.*; public class RR { private ArrayList<Process> processes; private ArrayList<Process> queue; private ArrayList<Process> completed; private Process current; private static int QUANTA_MAX = 99; private static int NUMBER_OF_PROCESSES_TO_MAKE = 30; private int quanta; private double totalTurnaroundTime; private double totalWaitTime; private double totalResponseTime; private double processesFinished; private String out; public RR(ArrayList<Process> processes) { this.processes = processes; this.queue = new ArrayList<Process>(); this.completed = new ArrayList<Process>(); out=""; execute(); } public static void main(String[] args) { ArrayList<Process> processes = new ArrayList<Process>(); for (int i = 1; i <= NUMBER_OF_PROCESSES_TO_MAKE; i++) { Process process = new Process("P" + i, i); processes.add(process); } Process.sortListByArrivalTime(processes); RR rr = new RR(processes); String table = ""; for (Process process : rr.getProcesses()) { table += "[Process: " + String.format("%3s", process.getName()) + ", Arrival time: " + String.format("%3d", process.getArrivalTime()) + ", Run time: " + String.format("%3d", process.getGivenExecutionTime()) + ", Priority: " + process.getPriority() + ", End time: " + String.format("%3d", process.getEndTime()) + ", Time started: " + String.format("%3d", process.getStartExecutionTime()) + ", Turnaround time: " + String.format("%3d", process.calculateTurnaroundTime()) + ", Wait time: " + String.format("%3d", process.calculateWaitTime()) + ", Response time: " + String.format("%3d", process.calculateResponseTime()) + "]\n"; } System.out.println(table); } public ArrayList<Process> getProcesses() { return this.completed; } public void execute() { quanta = 0; totalTurnaroundTime = 0; totalWaitTime = 0; totalResponseTime = 0; processesFinished = 0; while (quanta < QUANTA_MAX || !queue.isEmpty()) { if (quanta < QUANTA_MAX) { // Check the current time quanta, and add processes that arrive at the current time to the queue. for (Process process : processes) { if (process.getArrivalTime() <= quanta) { queue.add(process); // processes.remove(process); } } processes.removeAll(queue); } // Preemptive code block. if (!queue.isEmpty()) { // Get the process in the queue with the lowest remaining execution time. current = queue.remove(0); // If the current shortest process has not started yet, start it. if (current.getStartExecutionTime() < 0 && quanta < QUANTA_MAX) { current.setStartExecutionTime(quanta); } // If the process has started if (current.getStartExecutionTime() > -1) { // Represent it in the timeline out =out + ("[" + current.getName() + "]"); // Decrement the execution time remaining current.decrementExecutionTimeRemaining(); // Move the time splice quanta++; // If the shortest process is done (execution time remaining == 0) if (current.getExecutionTimeRemaining() <= 0) { // Set its end time at the current quanta current.setEndTime(quanta); // Add the finished process to the completed list. completed.add(current); processesFinished++; totalTurnaroundTime += current.calculateTurnaroundTime(); totalWaitTime += current.calculateWaitTime(); totalResponseTime += current.calculateResponseTime(); } else { // The process is not done, add it back into the queue. queue.add(current); } } } else { out = out + ("[*]"); quanta++; } } } public String getAverages() { String averages = "\n" +"Averages turnaround time: " + totalTurnaroundTime / processesFinished +"\n" + "Average wait time: " + totalWaitTime / processesFinished +"\n" + "Average response time: " + totalResponseTime / processesFinished +"\n" + "Throughput: " + processesFinished / quanta + " processes completed per quanta." +"\n"; /*System.out.println("\n"); System.out.println("Average turnaround time: " + totalTurnaroundTime / processesFinished); System.out.println("Average wait time: " + totalWaitTime / processesFinished); System.out.println("Average response time: " + totalResponseTime / processesFinished); System.out.println("Throughput: " + processesFinished / quanta + " processes completed per quanta."); System.out.println();*/ return averages; } public String getOut() { out = out +"\n"; return out; } }
devstudent123/Scheduling-Algorithms
RR.java
90
#include <iostream> #include <stdio.h> template <class t> using namespace std; void quick_sort(t a[], int low, int high) { t k; int i, j, flag = 1; if (low < high) { k = a[low]; i = low + 1; j = high; while (flag) { while ((a[i] <= k) && (i < j)) i++; while (a[j] > k) j--; if (i < j) swap(a, i, j); else flag = 0; } swap(a, low, j); quick_sort(a, low, j - 1); quick_sort(a, j + 1, high); } } template void swap(t1 a[], int x, int y) { t1 temp; temp = a[x]; a[x] = a[y]; a[y] = temp; } int main() { int i, n, a[20]; cout << "Enter the number of elements to be sort::"; cin >> n; cout << "Enter elements:\n"; for (i = 0; i < n; i++) cin >> a[i]; quick_sort(a, 0, n - 1); cout << "The sorted elements are:\n"; for (i = 0; i < n; i++) cout << a[i] << endl; ; }
mztriz/RTU-DigitalLibrary
Quicksort.java
91
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { // Create a Scanner object to read input from stdin. Scanner scan = new Scanner(System.in); // Read a full line of input from stdin and save it to our variable, inputString. String inputString = scan.nextLine(); // Close the scanner object, because we've finished reading // all of the input from stdin needed for this challenge. scan.close(); // Print a string literal saying "Hello, World." to stdout. System.out.println("Hello, World."); // TODO: Write a line of code here that prints the contents of inputString to stdout. System.out.println(inputString); } }
Snehaahh/30-DAY-CHALLENGE
Day 0
92
import java.util.*; public class Taxi implements Comparable { private Station origin; private int maxSize; private double startTime; private double endTime; private double returnTime; private double emptyMiles; private List<Trip> trips; public Taxi(int tripSize) { maxSize = tripSize; startTime = Double.POSITIVE_INFINITY; endTime = Double.NEGATIVE_INFINITY; returnTime = Double.NEGATIVE_INFINITY; emptyMiles = 0; trips = new ArrayList<Trip>(); origin = null; } public void assignTo(Station station) { if (origin == null) origin = station; } public void combine(Taxi t) { if (t.size() < this.size()) { System.out.println("size inconsistency"); return; } for (Trip trip: t.trips()) { this.addTrip(trip); } emptyMiles += t.emptyMiles; } public void addTrip(Trip trip) { // if (trip.size() > maxSize) return; // if trip size is too big for taxi... trips.add(trip); // update the start time of taxi, if needed if (trip.departTime() < startTime) startTime = trip.departTime(); // update teh end time if taxi, if needed if (trip.arriveTime() > endTime) endTime = trip.arriveTime(); } // update when this taxi will return to station public void updateReturn(double time) { if (time > returnTime) returnTime = time; } public void updateEmptyMiles(double miles) { emptyMiles += miles; } public Double startTime() { return (Double)startTime; } public int size() { return maxSize; } public Double endTime() { return (Double)endTime; } public Double returnTime() { return (Double)returnTime; } public boolean contains(Trip trip) { return trips.contains(trip); } //compare starttime with another taxi public int compareTo(Object obj) { Taxi other = (Taxi) obj; return ((Double)startTime).compareTo(other.startTime()); } public String oStation() { return origin.center(); } public List<Trip> trips() { return trips; } public double emptyMiles() { return emptyMiles; } public double vehicleMiles() { double vehicleMiles = 0; for (Trip trip : trips) { vehicleMiles += trip.tripMiles(); } return vehicleMiles; } }
nokafor/ORF376
Taxi4
93
// 8. String to Integer (atoi) // // Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). // // The algorithm for myAtoi(string s) is as follows: // // Read in and ignore any leading whitespace. // Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present. // Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored. // Convert these digits into an integer (i.e. "123" -> 123, "0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2). // If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1. // Return the integer as the final result. // Note: // // Only the space character ' ' is considered a whitespace character. // Do not ignore any characters other than the leading whitespace or the rest of the string after the digits. // // // Example 1: // // Input: s = "42" // Output: 42 // Explanation: The underlined characters are what is read in, the caret is the current reader position. // Step 1: "42" (no characters read because there is no leading whitespace) // ^ // Step 2: "42" (no characters read because there is neither a '-' nor '+') // ^ // Step 3: "42" ("42" is read in) // ^ // The parsed integer is 42. // Since 42 is in the range [-231, 231 - 1], the final result is 42. // Example 2: // // Input: s = " -42" // Output: -42 // Explanation: // Step 1: " -42" (leading whitespace is read and ignored) // ^ // Step 2: " -42" ('-' is read, so the result should be negative) // ^ // Step 3: " -42" ("42" is read in) // ^ // The parsed integer is -42. // Since -42 is in the range [-231, 231 - 1], the final result is -42. // Example 3: // // Input: s = "4193 with words" // Output: 4193 // Explanation: // Step 1: "4193 with words" (no characters read because there is no leading whitespace) // ^ // Step 2: "4193 with words" (no characters read because there is neither a '-' nor '+') // ^ // Step 3: "4193 with words" ("4193" is read in; reading stops because the next character is a non-digit) // ^ // The parsed integer is 4193. // Since 4193 is in the range [-231, 231 - 1], the final result is 4193. // // // Constraints: // // 0 <= s.length <= 200 // s consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'. // // Runtime 1 ms Beats 100.00% of users with Java // Memory 41.67 MB Beats 27.14% of users with Java class Solution { public int myAtoi(String s) { s = s.trim(); int n = s.length(); int i = 0; int sign = 1; if (n == 0) { return 0; } if (s.charAt(i)=='-') { sign = -1; } if (s.charAt(i)=='+' || s.charAt(i)=='-') { i++; } if (i >= n) { return 0; } int num = 0; while (i < n && Character.isDigit(s.charAt(i))) { int x = s.charAt(i) - '0'; if (num > Integer.MAX_VALUE / 10 || (num == Integer.MAX_VALUE / 10 && x > Integer.MAX_VALUE % 10)) { if (sign == 1) { return Integer.MAX_VALUE; } else { return Integer.MIN_VALUE; } } num = num * 10 + x; i++; } return num * sign; } }
ishuen/leetcode
8.java
94
// 6. ZigZag Conversion // The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) // // P A H N // A P L S I I G // Y I R // And then read line by line: "PAHNAPLSIIGYIR" // // Write the code that will take a string and make this conversion given a number of rows: // // string convert(string s, int numRows); // // // Example 1: // // Input: s = "PAYPALISHIRING", numRows = 3 // Output: "PAHNAPLSIIGYIR" // Example 2: // // Input: s = "PAYPALISHIRING", numRows = 4 // Output: "PINALSIGYAHRPI" // Explanation: // P I N // A L S I G // Y A H R // P I // Example 3: // // Input: s = "A", numRows = 1 // Output: "A" // // // Constraints: // // 1 <= s.length <= 1000 // s consists of English letters (lower-case and upper-case), ',' and '.'. // 1 <= numRows <= 1000 // Runtime: 2 ms, faster than 99.87% of Java online submissions for ZigZag Conversion. // Memory Usage: 39.2 MB, less than 80.00% of Java online submissions for ZigZag Conversion. // row = 3 // P [0,0], A[0,2], H[0,4],N[0,6] --> 0, 4, 8, 12 // A[1,0], P[1,1], L[1,2], S[1,3], I[1,4], I[1,5], G[1,6] --> 1, 3, 5, 7, 9, 11, 13 // Y[2,0], I[2,2], R[2,4] --> 2, 6, 10 // 1st row = 0 + 2 * n * (row - 1) // 2nd row = 1 + 2 * n * (row - 1) & (2 (row - 1) - curRowIndex) + 2 * n * (row - 1) // 3rd row = 2 + 2 * n * (row - 1) // row = 4 // P[0,0], I[0,3], N[0,6] --> 0, 6, 12 // A[1,0], L[1,2], S[1,3], I[1,5], G[1,6] --> 1, 5, 7, 11, 13 // Y[2,0], A[2,1], H[2,3], R[2,4] --> 2, 4, 8, 10 // P[3,0], I[3,3] --> 3, 9 // 1st row = 0 + 2 * n * (row - 1) // 2nd row = 1 + 2 * n * (row - 1) & (2 (row - 1) - curRowIndex) + 2 * n * (row - 1) // 3rd row = 2 + 2 * n * (row - 1) & (2 (row - 1) - curRowIndex) + 2 * n * (row - 1) // 4th row = 3 + 2 * n * (row - 1) class Solution { public String convert(String s, int numRows) { if (numRows == 1) return s; StringBuilder strBuilder = new StringBuilder(); int lastIndex = s.length() - 1; for (int i = 0; i < numRows; i++) { int index = i; int counter = 0; while (index <= lastIndex) { strBuilder.append(s.charAt(index)); if (counter == 0 && i != 0 && i != numRows - 1 && 2 * (numRows - 1) - i <= lastIndex) { strBuilder.append(s.charAt(2 * (numRows - 1) - i)); } counter++; index = i + counter * 2 * (numRows - 1); if (i != 0 && i != numRows - 1 && index <= lastIndex) { strBuilder.append(s.charAt(index)); index = 2 * (numRows - 1) - i + counter * 2 * (numRows - 1); } } } return strBuilder.toString(); } } // Runtime: 5 ms, faster than 73.63% of Java online submissions for ZigZag Conversion. // Memory Usage: 39.5 MB, less than 55.77% of Java online submissions for ZigZag Conversion. class Solution { public String convert(String s, int numRows) { if (numRows >= s.length() || numRows == 1) return s; char[] chars = s.toCharArray(); StringBuilder[] rows = new StringBuilder[numRows]; int rowNum = 0; for (int i = 0; i < chars.length; i++) { if (i < numRows) { rows[i] = new StringBuilder(); } rowNum = i % (2 * numRows - 2); if (rowNum >= numRows) rowNum = 2 * numRows - 2 - rowNum; rows[rowNum].append(chars[i]); } for (int i = 1; i < numRows; i++) { rows[0].append(rows[i]); } return rows[0].toString(); } }
ishuen/leetcode
6.java
95
// 2. Add Two Numbers // // You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. // // You may assume the two numbers do not contain any leading zero, except the number 0 itself. // // // // Example 1: // // // Input: l1 = [2,4,3], l2 = [5,6,4] // Output: [7,0,8] // Explanation: 342 + 465 = 807. // Example 2: // // Input: l1 = [0], l2 = [0] // Output: [0] // Example 3: // // Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] // Output: [8,9,9,9,0,0,0,1] // // // Constraints: // // The number of nodes in each linked list is in the range [1, 100]. // 0 <= Node.val <= 9 // It is guaranteed that the list represents a number that does not have leading zeros. // // Runtime 1 ms Beats 100.00% of users with Java // Memory 44.66 MB Beats 10.77% of users with Java /** * 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(); ListNode p = dummyHead; ListNode pointer1 = l1; ListNode pointer2 = l2; int extra = 0; while (pointer1 != null && pointer2 != null) { extra += pointer1.val + pointer2.val; ListNode cur = new ListNode(extra % 10); extra = extra / 10; p.next = cur; p = p.next; pointer1 = pointer1.next; pointer2 = pointer2.next; } while (pointer1 != null) { extra += pointer1.val; ListNode cur = new ListNode(extra % 10); extra = extra / 10; p.next = cur; p = p.next; pointer1 = pointer1.next; } while (pointer2 != null) { extra += pointer2.val; ListNode cur = new ListNode(extra % 10); extra = extra / 10; p.next = cur; p = p.next; pointer2 = pointer2.next; } if (extra != 0) { ListNode cur = new ListNode(extra); p.next = cur; } return dummyHead.next; } }
ishuen/leetcode
2.java
96
import java.util.*; import org.json.simple.*; import java.io.*; public class Q{ /* * This Stores state as a key, in String format * then double Q values for each action in state. */ HashMap<String, double[]> qMap = new HashMap<String, double[]>(); String mindImport = ""; public void importMind(String mind){ mindImport = mind; boolean isData = true; String mindData = ""; try{ mindData = strFromFile(mindImport); } catch(NoSuchElementException e){ System.out.println("Nothing in file... no data imported!"); isData = false; } if(isData){ reuseMind(mindData); } } /* * Lookup a state and find the best action to take * if more than single action is the same * pick random from bunch */ public int getBestAction(String state){ double[] actions = new double[9]; if(qMap.containsKey(state)){ actions = qMap.get(state); //return all action values } double highestQ = -5000; ArrayList<Integer> next = new ArrayList<Integer>(); //possible choices int choice = 0; for(int i=0; i < actions.length; i++){ if(actions[i] >= highestQ){ highestQ = actions[i]; choice = i; } } for(int i=0; i < actions.length; i++){ if(actions[i] == actions[choice]){ next.add(i); } } //return a random choice if more than one //or single choice if only one if(next.size()==1){ return next.get(0); } else if(next.size() > 1){ Random r = new Random(); int random = r.nextInt(next.size()); return next.get(random); } else{ //System.out.println(next.size()); Random r = new Random(); int random = r.nextInt(9); return random; } } /* * Get Q value for particular state/action */ public double getQ(String state, int action){ double[] actions = new double[9]; if(qMap.containsKey(state)){ actions = qMap.get(state); } return actions[action]; } /* * Update Q value for particular state/action with reward */ public void update_Q(String state, int action, double reward){ double[] actions = new double[9]; if(qMap.containsKey(state)){ actions = qMap.get(state); } actions[action] = reward; qMap.put(state, actions); } public void update_Q_reuse(String state, double[] actionsData){ qMap.put(state, actionsData); } /* This populates our Hashmap with the Q values from a file */ public void reuseMind(String data){ Object obj2 = JSONValue.parse(data); JSONObject arr = (JSONObject) obj2; parseJson(arr); } /* * Parse our Json object to pull array and object info */ public void parseJson(JSONObject arr){ Set<Object> set = arr.keySet(); Iterator<Object> iterator = set.iterator(); double[] thisk = new double[9]; String state = ""; while (iterator.hasNext()){ Object obj = iterator.next(); if (arr.get(obj) instanceof JSONArray){ //State and actions into Q state = obj.toString(); thisk = getArray(arr.get(obj)); update_Q_reuse(state, thisk); } else{ if (arr.get(obj) instanceof JSONObject) { parseJson((JSONObject) arr.get(obj)); } else{ System.out.println(obj.toString()); } } } } /* * Parse a JSONArray into a double array */ public double[] getArray(Object obj){ JSONArray jsonArr = (JSONArray) obj; double[] vals = new double[9]; for (int i=0; i < jsonArr.size(); i++) { vals[i] = (double)jsonArr.get(i); } return vals; } /* public void dump(){ System.out.println(qMap.toString()); } public static void main(String[] args){ double x = 100.0; String one = "000000001"; String two = "000200001"; String thr = "100200001"; Q q = new Q(); q.update_Q(two, 1, x); q.update_Q(two, 2, 10.0); q.update_Q(two, 4, 16.33); q.update_Q(one, 2, 200.0); q.update_Q(two, 8, 150.0); q.update_Q(thr, 3, 0.0); q.update_Q(thr, 5, 0.0); q.update_Q(thr, 4, -2.0); System.out.println(q.getBestAction(two)); System.out.println(q.getQ(two, 8)); System.out.println(q.getBestAction(one)); System.out.println(q.getBestAction(thr)); q.dump(); } */ //Print out board - Debugging purposes... public void printState(String state){ char[] sp = state.toCharArray(); System.out.println(sp[0]+" "+sp[1]+" "+sp[2]); System.out.println(sp[3]+" "+sp[4]+" "+sp[5]); System.out.println(sp[6]+" "+sp[7]+" "+sp[8]+"\n"); } public void dump(){ Set<String> enumk = qMap.keySet(); Iterator<String> iter = enumk.iterator(); while(iter.hasNext()) { String key = iter.next(); double[] val = qMap.get(key); System.out.print(key+": "); for(int i=0; i<val.length; i++){ System.out.print("a"+i+":"+val[i]+","); } System.out.println(); } } public void dumpJSON(){ JSONObject obj = new JSONObject(); JSONArray arr = new JSONArray(); double[] val = new double[9]; Set<Map.Entry<String, double[]>> set = qMap.entrySet(); String key = ""; for (Map.Entry<String, double[]> me : set) { key = me.getKey(); val = me.getValue(); for(int i=0; i<val.length; i++){ arr.add(val[i]); } obj.put(key, arr); arr = new JSONArray(); } String jsonString = JSONValue.toJSONString(obj); strToFile(mindImport, jsonString); } //write string data to a file public void strToFile(String filename, String data){ File file = new File(filename); try{ FileWriter dataf = new FileWriter(file); dataf.write(data); dataf.close(); } catch(FileNotFoundException e){ System.out.println("\nFile not found!"); } catch(IOException e){ System.out.println("\nIO Error!"); } } //Reads string from a file public String strFromFile(String filename){ String mydata = ""; File file = new File(filename); try{ Scanner data = new Scanner(file); mydata = data.nextLine(); data.close(); } catch(FileNotFoundException e){ System.out.println("\nFile not found!"); } return mydata; } }
maK-/Simple-Qlearning-XOs
Q.java
97
//{ Driver Code Starts import java.util.*; import java.io.*; class Node { int data; Node left, right; Node(int item) { data = item; left = right = null; } } class BinarySearchTree { public static Node root; BinarySearchTree() { root = null; } void insert(int key) { root = insertRec(root, key); } Node insertRec(Node root, int key) { if (root == null) { root = new Node(key); return root; } if (key < root.data) root.left = insertRec(root.left, key); else if (key > root.data) root.right = insertRec(root.right, key); return root; } public static void inorder() { inorderRec(root); } public static void inorderRec(Node root) { if (root != null) { inorderRec(root.left); System.out.print(root.data); inorderRec(root.right); } } // Driver Program to test above functions public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int []a=new int[n]; BinarySearchTree obj1=new BinarySearchTree(); for(int i=0;i<n;i++) { int b=sc.nextInt(); obj1.insert(b); } //inorder(); Solution obj=new Solution(); boolean k=obj.isDeadEnd(root); if(k==true) System.out.println("1"); else System.out.println("0"); } } } // } Driver Code Ends /*class Node { int data; Node left, right; Node(int item) { data = item; left = right = null; } }*/ //Function should return true if a deadEnd is found in the bst otherwise return false. class Solution{ public static void Inorder(Node root,ArrayList<Integer> l){ if(root == null){ return; } Inorder(root.left,l); l.add(root.data); Inorder(root.right,l); return; } public static boolean isDeadNode(Node root,ArrayList<Integer> l){ if(root == null){ return false; } if(root.left == null && root.right == null){ if(l.contains(root.data-1) && l.contains(root.data+1)){ return true; } } return isDeadNode(root.left,l) || isDeadNode(root.right,l); } public static boolean isDeadEnd(Node root){ ArrayList<Integer> l = new ArrayList<>(); l.add(0); Inorder(root,l); return isDeadNode(root,l); } }
dhruvabhat24/Geeks-For-Geeks-December
1.java
98
import java.util.*; class Member{ String name,address; int age; float salary; long phoneno; void printsal() { System.out.println("The Member's salary is "+salary); } } class Employee extends Member { String spel; Employee(String n,String ad,int ag,float sal,long ph,String spe) { name=n; address=ad; age=ag; salary=sal; phoneno=ph; spel=spe; } } class Manager extends Member { String dept; Manager(String n,String ad,int ag,float sal,long ph,String dep) { name=n; address=ad; age=ag; salary=sal; phoneno=ph; dept=dep; } } public class Main{ public static void main(String[] args) { Scanner sc = new Scanner (System.in); System.out.println("Enter the Name of the Employee"); String n = sc.next(); System.out.println("Enter the age of the Employee"); int ag = sc.nextInt(); System.out.println("Enter the Phone number the Employee"); long ph = sc.nextLong(); System.out.println("Enter the address of the Employee"); String ad = sc.next(); System.out.println("Enter the salary of the Employee"); float sal = sc.nextFloat(); System.out.println("Enter the specialization of the Employee"); String spe = sc.next(); Employee ob = new Employee(n,ad,ag,sal,ph,spe); System.out.println("Enter the Name of the Manager"); n = sc.next(); System.out.println("Enter the age of the Manager"); ag = sc.nextInt(); System.out.println("Enter the Phone number the Manager"); ph = sc.nextLong(); System.out.println("Enter the address of the Manager"); ad = sc.next(); System.out.println("Enter the salary of the Manager"); sal = sc.nextFloat(); System.out.println("Enter the department of the Manager"); spe = sc.next(); Manager ob1 = new Manager(n,ad,ag,sal,ph,spe); System.out.println("NAME\tAGE\tPHONE NO\tADDRESS\tSPECIALIZATION\\DEPARTMENT");//optional i love aesthetics so tehee System.out.println(ob.name+"\t"+ob.age+"\t"+ob.phoneno+"\t"+ob.address+"\t"+ob.spel); System.out.println(ob1.name+"\t"+ob1.age+"\t"+ob1.phoneno+"\t"+ob1.address+"\t"+ob1.dept); ob.printsal(); ob1.printsal(); } }
Welding-Torch/Java-Prac
7.java
99
//{ Driver Code Starts //Initial Template for Java import java.util.*; import java.io.*; class Node { int data; Node left, right; Node(int val) { data = val; left = right = null; } } // } Driver Code Ends //User function Template for Java /*Structure of the Node of the BST is as class Node { int data; Node left, right; Node(int val) { data = val; left = right = null; } } */ class Solution { public static int countPairs(Node root1, Node root2, int x) { // Code here HashSet<Integer> set=new HashSet<>(); Queue<Node> q=new LinkedList<>(); q.add(root1); while(!q.isEmpty()){ Node curr=q.poll(); set.add(curr.data); if(curr.left!=null){ q.add(curr.left); } if(curr.right!=null){ q.add(curr.right); } } int count=0; q.add(root2); while(!q.isEmpty()){ Node curr=q.poll(); int data=x-curr.data; if(set.contains(data)){ count++; } if(curr.left!=null){ q.add(curr.left); } if(curr.right!=null){ q.add(curr.right); } } return count; } } //{ Driver Code Starts. public class Main { static FastIO f; // Function to Build Tree static Node buildTree(String str) { // Corner Case if(str.length() == 0 || str.charAt(0) == 'N') return null; // Creating array of strings from input // string after spliting by space String[] ip = str.split(" "); // Create the root of the tree Node root = new Node(Integer.parseInt(ip[0])); // Push the root to the queue Queue<Node> queue = new LinkedList<>(); queue.add(root); // Starting from the second element int i = 1; while (!queue.isEmpty() && i < ip.length) { // Get and remove the front of the queue Node currNode = queue.poll(); // Get the current node's value from the string String currVal = ip[i]; // If the left child is not null if (!currVal.equals("N")) { // Create the left child for the current Node currNode.left = new Node(Integer.parseInt(currVal)); // Push it to the queue queue.add(currNode.left); } // For the right child i++; if (i >= ip.length) break; currVal = ip[i]; // If the right child is not null if (!currVal.equals("N")) { // Create the right child for the current node currNode.right = new Node(Integer.parseInt(currVal)); // Push it to the queue queue.add(currNode.right); } i++; } return root; } public static void main(String args[]) throws IOException { f = new FastIO(); int t = f.nextInt(); while(t-->0) { String tree1 = f.nextLine(), tree2 = f.nextLine(); Node root1 = buildTree(tree1), root2 = buildTree(tree2); int x = f.nextInt(); f.out(Solution.countPairs(root1, root2, x) + "\n"); } f.flush(); } } class FastIO { BufferedReader br; PrintWriter bw, be; StringTokenizer st; public FastIO() { br = new BufferedReader(new InputStreamReader(System.in)); bw = new PrintWriter(System.out); be = new PrintWriter(System.err); st = new StringTokenizer(""); } private void read() throws IOException { st = new StringTokenizer(br.readLine()); } public String nextLine() throws IOException { return br.readLine(); } public String next() throws IOException { while(!st.hasMoreTokens()) read(); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public float nextFloat() throws IOException { return Float.parseFloat(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public void out(String s) throws IOException { bw.print(s); } public void flush() throws IOException { bw.flush(); be.flush(); } public void err(String s) throws IOException { be.print(s); } } // } Driver Code Ends
dhruvabhat24/Geeks-For-Geeks-December
3.java
100
/* The design principle used in the provided code is the Open/Closed Principle(OCP). This code also illustrates the ISP. The Open/Closed Principle states that software entities (classes, modules, functions, etc.) should be open for extension but closed for modification. In other words, you should be able to extend the behavior of a system without modifying its existing code. */ interface Shape { // when I am changing getArea() to double from float it is giving nosuchmethoderror exception in rectangle class and in line no. 65 float getArea(); } class Rectangle implements Shape { private float length; private float width; public Rectangle(float length, float width) { this.length = length; this.width = width; } @Override public float getArea() { return length * width ; } } class Square implements Shape { private float side; public Square (float side){ this.side = side; } @Override public float getArea(){ return side * side; } } class Circle implements Shape { private float radius; public Circle (float radius){ this.radius = radius; } @Override public float getArea(){ // this formula is wrong return radius * radius; // this formula is right // return Math.PI * radius * radius; // but getArea is of float type and it cannot convert float to double } } public class O { public static void main(String [] arg){ Rectangle R = new Rectangle(4, 5); double rectangleArea = R.getArea(); System.out.println("Area of Rectangle : " + rectangleArea); Square S = new Square(3); double SquareArea = S.getArea(); System.out.println("Area of Square : "+ SquareArea); Circle C = new Circle(21); double circleArea = C.getArea(); System.out.println("Area of Circle : "+circleArea); } }
Lakhan-Gurjar/SOLID-Design-Principles
O.java