I tried to reprogramm this and fit it to my needs (calculating n^k with recursion). But something seems faulty, because I first got the txt files without any text in it; now after changing and trying to bugfix I get nothing at all :(
https://www.youtube.com/watch?v=br_TEuE8TbY
package Uebung3;
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Hauptthread implements Runnable {
//int start;
//int stop;
boolean haupt=false;
String file;
static int n, k;
public Hauptthread(int startvalue, int stopvalue, String file, boolean h){
n= startvalue;
k=stopvalue;
this.file=file;
haupt=h;
}
public void run(){
ArrayList<Double> binominal=new ArrayList<>();
if (haupt=false) {
for (int i = n; i <= k; i++) {
binominal.add(binomial(n,k));
}
try{
PrintWriter print=new PrintWriter(new File(file));
for (int i = 0; i < binominal.size() ; i++) {
print.println("Test");
print.println(binominal.get(i));
}
}
catch(Exception e){
System.out.println("Error " + e.getMessage());
}
}
}
double binomial(int n, int k) {
if (k == 0) {
return 1; }
else {
return (((double)n/k) * binomial(n-1, k-1)); }
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
package Uebung3;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Uebung3 {
public static int threadcount=4;
public static int n, k;
public static int stop=k;
public static void main(String[] args) {
/*
int n = Integer.parseInt(JOptionPane.showInputDialog("n = "));
int k = Integer.parseInt(JOptionPane.showInputDialog("k = "));
if (n < 0 || k < 0 || k > n) {
JOptionPane.showMessageDialog(null, "Ungueltige Eingabe"); }
else {
JOptionPane.showMessageDialog(null, "Rechne" );
//JOptionPane.showMessageDialog(null, "n über k = " +binomial(n, k));
}
*/
System.out.println("Erstelle Threads...");
int erhoehe=20/threadcount;
int start=2;
ArrayList <Thread> threads = new ArrayList<>();
for (int i = 0; i < threadcount; i++) {
//if(!((i+1)==threadcount)){
if(start==10){
threads.add(new Thread(new Hauptthread(start, erhoehe, i+".txt",false)));
}
else {
threads.add(new Thread(new Hauptthread(start, erhoehe, i+".txt",true)));
}
}
for (int i = 0; i < threads.size(); i++) {
threads.get(i).start();
}
for (int i = 0; i < threads.size(); i++) {
try {
threads.get(i).join();
} catch (Exception e) {
System.out.println("Error" +e.getMessage());
}
}
}
}
Related
I have these two classes:
import java.util.ArrayList;
import java.util.Arrays;
public class Giocatore {
private String nome;
private ArrayList<Cartella> cartelle;
public Giocatore(String nome, int numeroCartelle) {
this.nome = nome;
for (int i = 0; i < numeroCartelle; i++) {
cartelle.add(new Cartella().creazioneCartella());
}
}
#Override
public String toString() {
return "Giocatore" + " nome=" + nome + ", cartelle=" + cartelle + "]";
}
}
and
import java.util.Random;
public class Cartella {
private int[] cartella;
public Cartella() {
cartella = new int[15];
}
public int[] creazioneCartella() {
Random random = new Random();
int n = random.nextInt(90 + 1) + 1;
for (int i = 0; i < cartella.length; i++) {
if (i > 0) {
for (int j = 0; j < i; j++) {
if (n == cartella[j]) {
n = random.nextInt(90 + 1) + 1;
j--;
}
}
}
cartella[i] = n;
}
return cartella;
}
public void stampaCartella() {
for (int i = 0; i < cartella.length; i++) {
System.out.print(cartella[i] + " ");
}
System.out.println();
}
public int[] getCartella() {
return cartella;
}
public void setCartella(int[] cartella) {
this.cartella = cartella;
}
}
i used the class Cartella as an arraylist in Giocatore, now i want to add an array into that arraylist using the method creazioneCartella(), but every time the compiler suggest me to change the method creazioneCartella into an element of Cartella. How can i add that array into that list? i've tried different methods like Arrays.asList(array) but nothing
I am working on a selection sort in Java. It will prompt a user to enter in 10 names and then sort them alphabetically. It is sorting some of them but not completely and cannot figure out why it is sorting some values and not others. I believe I have implemented the sort and swap correctly but I feel as though I am missing something. Any help is appreciated as always.
import java.util.*;
public class sortingProgram {
static String studentName[] = new String[10];
static int i;
static Scanner scnr = new Scanner(System.in);
public static void enterNames() {
for (i = 0; i < studentName.length; i++) {
System.out.println("Please enter a student name: ");
studentName[i] = scnr.nextLine();
}
}
public static void sortNames(String sortArray[]) {
int smallindex;
for (int i = 0; i < sortArray.length; i++) {
smallindex = i;
for (int j = i + 1; j < sortArray.length; j++) {
if (sortArray[j].compareTo(sortArray[smallindex]) < 0) {
smallindex = j;
if (smallindex != i)
swap(sortArray, smallindex, i);
}
}
}
System.out.println(Arrays.toString(sortArray));
}
public static void swap(Object a[], int i1, int j1) {
Object temp = a[i1];
a[i1] = a[j1];
a[j1] = temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
enterNames();
sortNames(studentName);
}
}
You are doing your swap too early. You need to wait until the smallest has been determined before swapping. You are swapping whenever you detect a smaller one.
public static void sortNames(String sortArray[]) {
for (int i = 0; i < sortArray.length; i++) {
int smallindex = i;
for (int j = i + 1; j < sortArray.length; j++) {
if (sortArray[j].compareTo(sortArray[smallindex]) < 0) {
smallindex = j;
// Move this.
//if (smallindex != i)
// swap(sortArray, smallindex, i);
}
}
// To here.
if (smallindex != i)
swap(sortArray, smallindex, i);
}
}
public static void swap(Object a[], int i1, int j1) {
Object temp = a[i1];
a[i1] = a[j1];
a[j1] = temp;
}
private void test() {
String[] names = {"C", "B", "A", "9"};
System.out.println(Arrays.toString(names));
sortNames(names);
System.out.println(Arrays.toString(names));
}
use below changes in your program.
import java.util.*;
public class SortingProgram {
static String studentName[] = new String[10];
static int i;
static Scanner scnr = new Scanner(System.in);
public static void enterNames() {
for (i = 0; i < studentName.length; i++) {
System.out.println("Please enter a student name: ");
studentName[i] = scnr.nextLine();
}
}
public static void sortNames(String sortArray[]) {
int smallindex;
for (int i = 0; i < sortArray.length; i++) {
smallindex = i;
for (int j = i + 1; j < sortArray.length; j++) {
if (sortArray[j].compareTo(sortArray[smallindex]) < 0) {
smallindex = j;
//if (smallindex != i) No need here
//swap(sortArray, smallindex, i);
}
}
//place your swaping code here
if (smallindex != i)
swap(sortArray, smallindex, i);
}
System.out.println(Arrays.toString(sortArray));
}
public static void swap(Object a[], int i1, int j1) {
Object temp = a[i1];
a[i1] = a[j1];
a[j1] = temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
enterNames();
sortNames(studentName);
}
}
after making these changes your program works. your code not works properly because you perform swap early.
So I'm getting this weird error that I can't seem to figure out, and it's way too long to google so my only help is you guys.
This is the error I'm getting:
https://i.imgur.com/5BWeiCk.png
Here's the class:
import java.util.Scanner;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Collections;
public class Ordliste {
private ArrayList<String> liste = new ArrayList<String>();
private int teller, total = 0;
public void lesBok (String filnavn) throws Exception{
Scanner fil = new Scanner(new File(filnavn));
while(fil.hasNextLine()){
liste.add(fil.next());
} fil.close();
}
public void leggTilOrd(String ord){
for(int t = 0; t < liste.size(); t++)
if(liste.get(t).equalsIgnoreCase(ord)){
teller++;
} total = total + teller + 1;
System.out.println("Ordet " + ord + " forekommer " + teller + " ganger i ordlisten og har naa blitt oekt til " + total + "!");
if (liste.stream().noneMatch(s -> s.equalsIgnoreCase(ord))){
liste.add(ord);
}
}
public Ord finnOrd(String tekst){
Ord finneord = new Ord(tekst);
for(int t = 0; t < liste.size(); t++)
if(liste.get(t).equalsIgnoreCase(tekst)){
return finneord;
} return null;
}
public int antallOrd(){
Set<String> ulikeOrd = new HashSet<String>(liste);
int unique = ulikeOrd.size();
System.out.println(unique);
return unique;
}
public int antallForekomster(String tekst){
int counter = 0;
for(int t = 0; t < liste.size(); t++)
if(liste.get(t).equalsIgnoreCase(tekst))
counter++;
return counter;
}
public Ord[] vanligste5(){
ArrayList<Ord> oftest = new ArrayList<Ord>();
oftest.add(liste.get(0));
int p = -1;
for(int t = 0; t < liste.size(); t++){
for(int i = 0; i < oftest.size(); i++){
if(liste.get(t).hentAntall() >= oftest.get(i).hentAntall()){
p = i;
break;
}
}
if(p == -1){
oftest.add(liste.get(t));
} else {
oftest.add(p, liste.get(t));
}
} Ord[] array = new Ord[5];
return oftest.subList(0,5).toArray(array);
}
}
Here's the Ord class:
import java.util.Scanner;
import java.io.File;
public class Ord {
private String tekstord;
private int teller = 0;
public Ord(String tekst){
tekstord = tekst.toLowerCase();
teller++;
}
public String toString(){
return tekstord;
}
public int hentAntall() {
return teller;
}
public void oekAntall(){
teller++;
}
public int hentLengde() {
int lengde = tekstord.length();
return lengde;
}
public int plassiDokument(){
int lengde = tekstord.length();
teller = teller * lengde;
return teller;
}
}
You are getting the error because oftest holds list of Ord objects not list of Strings.
You can do something like this oftest.add(new Ord(liste.get(0)));.
In this part of code you have issue:
public Ord[] vanligste5(){
ArrayList<Ord> oftest = new ArrayList<Ord>();
oftest.add(liste.get(0)); // error place
You are trying to add String to collection of Ord. It is not legal operation in java. You should rework this code block according to your specifications.
I am learning how to implement basic algorithms in Java, so i am a newbie in this environment. I am trying to implement Merge Sort algorithm using ArrayList where program will read data (Integer in each line) from file and produce sorting result using Merge Sort. However, my code is showing same result as it has not sorted anything out! I would be very glad if someone can identify where did I do my mistake. As i am a beginner, the code is very simple, not optimized and not very fast in performance probably.
Here is my code:
public class MergeSortExp1 {
public static void main(String[] args) {
ArrayList<Integer>number = new ArrayList<Integer>();
Scanner myScanner = null;
try {
myScanner = new Scanner(new File("/Users/Sabbir/Desktop/workload.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while(myScanner.hasNextInt()){
number.add(myScanner.nextInt());
}
System.out.println("Before sorting" +number);
number=mergeSort(number);
System.out.println("Sorted Array =" +number);
}
public static ArrayList<Integer> mergeSort( ArrayList<Integer> Input)
{
if (Input.size() ==1){
return Input;
}
else {
int mid= Input.size()/2;
ArrayList<Integer> left= new ArrayList<Integer>(mid);
ArrayList<Integer> right=new ArrayList<Integer>(Input.size()-mid);
for (int i = 0; i < mid; i++) {
left.add(Input.get(i));
}
for (int i = 0; i < Input.size()-mid; i++) {
right.add(Input.get(i));
}
left=mergeSort(left);
right=mergeSort(right);
merge(left,right,Input);
}
return Input;
}
public static void merge (ArrayList<Integer>left,ArrayList<Integer>right,ArrayList<Integer>Input)
{
int i1=0;// left Index
int i2=0;// right Index
int InputIndex=0;
for (int i = 0; i < Input.size(); i++) {
if (i2>=right.size() || (i1<left.size() && left.get(i)<=right.get(i)))
{
Input.set(InputIndex,left.get(i1));
InputIndex++;
}
else {
Input.set(InputIndex, right.get(i2));
InputIndex++;
}
}
}
}
If your merge method is Ok (I don't test it), you forget to merge left and right to input, edit your code as shown below and re-try:
// This is called recursion. Calling a method again within the
//method until the value of left and right becomes 1.
left=mergeSort(left);
right=mergeSort(right);
merge(left,right,Input);
hope helped you!
One more variant:
private static <T extends Comparable<T>> List<T> mergeSort(List<T> unsortedList) {
if (unsortedList.size() <= 1) {
return unsortedList;
}
List<T> sortedList = new ArrayList<>(unsortedList.size());
List<T> leftList = mergeSort(unsortedList.subList(0, unsortedList.size() / 2));
List<T> rightList = mergeSort(unsortedList.subList(unsortedList.size() / 2, unsortedList.size()));
int leftIdx = 0;
int rightIdx = 0;
int resultIdx = 0;
while (leftIdx < leftList.size() && rightIdx < rightList.size()) {
if (leftList.get(leftIdx).compareTo(rightList.get(rightIdx)) <= 0) {
sortedList.add(resultIdx, leftList.get(leftIdx));
leftIdx++;
} else {
sortedList.add(resultIdx, rightList.get(rightIdx));
rightIdx++;
}
resultIdx++;
}
while (leftIdx < leftList.size()) {
sortedList.add(resultIdx, leftList.get(leftIdx));
leftIdx++;
resultIdx++;
}
while (rightIdx < rightList.size()) {
sortedList.add(resultIdx, rightList.get(rightIdx));
rightIdx++;
resultIdx++;
}
return sortedList;
}
import java.util.ArrayList;
import java.io.*;
import java.util.*;
public class Mergesort1 {
public static void main(String[] args) {
ArrayList<Integer> values = new ArrayList<Integer>();
int zeilen = 0;
try{
FileInputStream in = new FileInputStream(args[0]);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while((line = reader.readLine()) != null){
values.add(Integer.parseInt(line));
zeilen++;
}
try{
FileOutputStream out = new FileOutputStream(args[1]);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
sort(values); //sortien array list
for (int i=0; i<values.size(); i++){
writer.write("" + values.get(i));
writer.newLine();
}
writer.close();
}
catch(Exception e){
System.out.println(e);
}
}
catch(Exception e){
System.out.println(e);
}
}
public static ArrayList<Integer> sort( ArrayList<Integer> values)
{
if (values.size() ==1){
return values;
}
else {
int mid= values.size()/2;
ArrayList<Integer> left= new ArrayList<Integer>(mid);
ArrayList<Integer> right=new ArrayList<Integer>(values.size()-mid);
for (int i = 0; i < mid; i++) {
left.add(values.get(i));
}
for (int i = mid; i < values.size(); i++) {
right.add(values.get(i));
}
left=sort(left);
right=sort(right);
merge(left,right,values);
}
return values;
}
public static void merge (ArrayList<Integer>left,ArrayList<Integer>right,ArrayList<Integer>values)
{
int i1=0;// left Index
int i2=0;// right Index
int InputIndex=0;
for (int i = 0; i < values.size(); i++) {
if(i1==left.size()){
values.set(i, right.get(i2));
i2++;
}
else{
if (i2==right.size()){
values.set(i,left.get(i1));
i1++;
}
else{
if (left.get(i1)<=right.get(i2)) {
values.set(i,left.get(i1));
i1++;
}
else {
if (left.get(i1)>=right.get(i2)) {
values.set(i, right.get(i2));
i2++;
}
}
}
}
}
}
}
I'm trying to solve this question:
https://www.hackerrank.com/contests/projecteuler/challenges/euler003/submissions/code/2977447
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of a given number N?
Input Format
First line contains T, the number of test cases. This is followed by T lines each containing an integer N.
Output Format
For each test case, display the largest prime factor of N.
Constraints
1≤T≤10
10≤N≤1012
and my code below gets a timeout error for the fifth test (which we don't know about the actual content). any thought why did it fail the test? thanks
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
/* Author: Derek Zhu
* 1and1get2#gmail.com
* https://www.hackerrank.com/contests/projecteuler/challenges/euler003
* */
// The part of the program involving reading from STDIN and writing to STDOUT has been provided by us.
public class Solution {
public static boolean D = true;
static BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
static StringBuilder out = new StringBuilder();
public static void main(String[] args) throws NumberFormatException,
IOException {
int numOfCases = Integer.parseInt(in.readLine());
for (int i = 0; i < numOfCases; i++){
calculateCase(Long.parseLong(in.readLine()));
}
}
private static void calculateCase(Long input) throws IOException{
if (D) System.out.println("Processing: " + input);
long largestPF = prime(input);
if (D) System.out.print("Final calculate: ");
System.out.println(largestPF);
}
private static long prime(long n){
long i = 2;
while ( n % i != 0 && i < n){
i ++;
}
if (D) System.out.println("found i: " + i);
if (i < n){
return prime(n/i);
} else {
return n;
}
}
public static int primeFactors(BigInteger number) {
BigInteger copyOfInput = number;
int lastFactor = 0;
for (int i = 2;
BigInteger.valueOf(i)
.compareTo(copyOfInput) <= 0; i++) {
if (copyOfInput.mod(BigInteger.valueOf(i))
.compareTo(BigInteger.ZERO) == 0)
{
lastFactor = i;
copyOfInput = copyOfInput
.divide(BigInteger.valueOf(i));
i--;
}
}
return lastFactor;
}
}
Thanks #ajb
as it turns out, taking another method would be much efficient.
private static long method2(long NUMBER){
long result = 0;
for(int i = 2; i < NUMBER; i++) {
if(NUMBER % i == 0 && isPrime(NUMBER / i)) {
result = NUMBER / i;
break;
}
}
return result;
}
private static boolean isPrime(long l) {
for(long num = 2, max = l / 2 ; num < max; num++) {
if(l % num == 0) {
return false;
}
}
return true;
}
complete code with comparison of time can be found here:
https://github.com/1and1get2/hackerrank/blob/master/Contests/ProjectEuler%2B/003_LargestPrimeFactor/src/Solution.java
if (NUMBER<2){
return -1;
}
int result = 0;
for (int i =2; NUMBER>i; i++ ){
if (NUMBER%i==0){
result = NUMBER / i;
if (result/1==result && result/result==1 && result%2!=0 && result%3!=0 && result%5!=0 && result%7!=0){
break;
}
}
}
return result;
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) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
int count,k=0,n=0;
long arr[]=new long[1000000];
long arr1[]=new long[1000000];
long arr2[]=new long[10000000];
for(int a0 = 0; a0 < t; a0++){
arr[a0] = in.nextLong();
}
for(int i=0;i<t;i++)
{
for(int j=2;j<=arr[i];j++)
{
if(arr[i]%j==0)
{
arr1[k]=j;
k++;
}
}
for(int l=0;l<k;l++)
{
count=0;
for(int m=1;m<=arr1[l];m++)
{
if(arr1[l]%m==0)
{
count++;
}
}
if(count==2)
{
arr2[n]=arr1[l];
n++;
}
}
Arrays.sort(arr2);
System.out.println(arr2[arr2.length-1]);
}
}
}