prime1 spoj generating prime numbers between two number - java

package primesieve1;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Primesieve1 {
public boolean[] sieveOfEratosthenes(int max){
boolean[] primeno; //defaults to false
primeno = new boolean[max];
for(int i=2; i<max; i++ ){primeno[i]=true;}
for(int i=2; i<Math.sqrt(max);i++){
if(primeno[i] == true){
//all multiples of i*i, except i, are not primeno
for(int j = i + i; j<max; j=j+i){
primeno[j]=false;
}
}
}
return primeno;
}
public void printTrue(boolean[] arr){
for(int i=0; i<arr.length; i++){
if(arr[i]==true){
System.out.print(i + ", ");
}
}
}
public static void main(String[] args) {
System.out.println("enter limit");
Scanner sc = new Scanner(new InputStreamReader(System.in));
int a = sc.nextInt();
boolean a1[];
Primesieve1 obj = new Primesieve1();
a1 = obj.sieveOfEratosthenes(a);
obj.printTrue(a1);
}
}
giving out this error didnt understand why
java.lang.OutOfMemoryError: Java heap space

Although I'm not 100% sure I think a boolean[] still uses about 1 byte per entry. Max will probably get quite big so even increasing the memory for the JVM will probably not do the trick.
One thing you can do however is not use a boolean[] but a BitSet instead, this way you'll only use 1 bit per number and thus you can probably cover until the max value of int.

Related

Print boolean input in a 2d array using for loop

I have an assignment where I need to create a 3x5 array and ask the user for a boolean input. I then need to print the user input into every cell of the array. I'm stuck on how to use a for loop to enter the user input into the array. I also have to do this using methods. My code so far is:
import java.util.*;
public class TrueFalse
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
boolean myA[][] = new boolean [5][3];
popArray(myA);
}
public static void popArray(boolean answ, boolean pArray[][])
{
System.out.println("Enter true or false.");
answ = console.nextBoolean();
for (int i=0; i<pArray.length; i++)
{
pArray[i] = answ;
}
}
}
You're not far off:
for (int i=0; i<pArray.length; i++) {
for (int j=0; i<pArray[i].length; j++) {
System.out.println("Enter true or false.");
pArray[i][j] = console.nextBoolean();
}
}
will do the trick. Note you defined a matrix with 5 rows and 3 columns, the opposite of what you write in the text. Also note I'm checking nothing here.
Your code is not far off. Try iterating over the bounds of the array in your popArray method:
public static void popArray(boolean pArray[][]) {
for (int r=0; r < pArray.length; ++r) {
for (int c=0; c < pArray[0].length; ++c) {
System.out.println("Enter true or false.");
boolean answ = console.nextBoolean();
pArray[r][c] = answ;
}
}
}
One convenient option for printing your 2D array is Arrays.deepToString(), e.g.
System.out.println(Arrays.deepToString(pArray));
To make 3*5 array of boolean you should do
boolean myA[][] = new boolean [3][5];
And make nested loop. and you can index the value to the array variable myA[ i ][ j ]
for(int i=0;i<3;i++){
for(int j=0;j<5;j++){
myA[i][j]=false;
}
}
In your code you have a two dimensional array but your not assessing it correctly. You can visualized your 2d array as a matrix with 5 rows and 3 columns. So to assess every location you need to specify the row and column numbers. Your code should look like this:
private static int ROWS= 5;
private static int COLUMNS = 3;
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
boolean myA[][] = new boolean [ROWS][COLUMNS];
popArray(myA);
}
public static void popArray(boolean answ, boolean pArray[][])
{
System.out.println("Enter true or false.");
for (int i=0; i<COLUMNS ; i++)
{
for (int j=0; j<ROWS; j++)
{
pArray[i][j] = console.nextBoolean();
}
}
}

Bubble Sort numbers from file in java

I am trying to bubble sort numbers from a text file, I understand how to bubble sort and how to use a text file. But have never used both of them at the same time. I tried bubble sorting an array and just trying to figure out how to replace that array with a text file. If someone can explain to me how to get the bubble sort to read a text file it would be greatly appreciated. I am new to java and it is sometimes confusing to combine 2 different things I have learned into 1 program.
Here is my bubble sort that solves the array:
public static void main(String[] args)
{
int number[]={7,13,4,5,62,3,1,3,45};
int temp;
boolean fixed=false;
while(fixed==false){
fixed = true;
for (int i=0; i <number.length-1;i++){
if (number[i]>number[i+1]){
temp = number [i+1];
number[i+1]=number[i];
number[i]=temp;
fixed=false;
}
}
}
for (int i=0; i<number.length;i++){
System.out.println(number[i]);
}
}
}
Use Scanner class !
File file=new File("file.txt");
Scanner sc=new Scanner(file);
int arr[]=new int[100];
int i=0;
while(sc.hasNextLine()){
arr[i]=sc.nextInt();
i++;
}
Don't just hard code the array..!
Suppose the content of your file is a list of number separated by some delimiter say single space " "
Use:
File file=new File("file.txt");
Scanner sc=new Scanner(file);
String arr[] = sc.nextLine().split(" ");
That is it.
Once you have got the array u can play around with it..!
Reading a file has nothing to do with bubble sort. You can read the file to create an array of integers and then use the usual bubble sort algorithm to sort it
You can do like this:
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void bubbleSort(int[] num ) {
int j;
boolean flag = true; // set flag to true to begin first pass
int temp; //holding variable
while ( flag ) {
flag= false; //set flag to false awaiting a possible swap
for( j=0; j < num.length -1; j++ ) {
if ( num[ j ] < num[j+1] ) {
temp = num[ j ]; //swap elements
num[ j ] = num[ j+1 ];
num[ j+1 ] = temp;
flag = true; //shows a swap occurred
}
}
}
}
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("numbers.txt"));
int [] numbers = new int [256];
int i = 0;
while(scanner.hasNextInt()){
numbers[i++] = scanner.nextInt();
}
bubbleSort(numbers);
System.out.println(Arrays.toString(numbers));
}
}

CodeEval Overlapping Rectangles code review

I have been testing my code for the overlapping rectangles challenge on codeeval. I feel my code is close to the solution as I have tested it on my machine and it appears correct. Codeeval is picky however and won't execute the code, claiming it is hanging.No further information is given. It has done this in the past but that was due to me not closing my scanner at the end. Am I violating a similar principle here?
Any recommendations on finding the solution simpler or better coding practices is appreciated.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("C:/Users/minda_000/Desktop/text.txt");
FileReader fr = new FileReader(file);
Scanner scan = new Scanner(fr);
scan.useDelimiter(",");
boolean flag = true;
while (scan.hasNextLine()) {
String line = scan.nextLine();
Scanner scanline = new Scanner(line);
scanline.useDelimiter(",");
int lxa = scanline.nextInt();
int lya = scanline.nextInt();
int rxa = scanline.nextInt();
int rya = scanline.nextInt();
int lxb = scanline.nextInt();
int lyb = scanline.nextInt();
int rxb = scanline.nextInt();
int ryb = scanline.nextInt();
int[] contentsofx = contentsOfX(lxa, rxa);
int[] contentsofy = contentsOfY(lya, rya);
int[] contentsofx2 = contentsOfX(lxb, rxb);
int[] contentsofy2 = contentsOfY(lyb, ryb);
scanline.close();
for (int i = 0; i < contentsofx.length; i++) {
for (int j = 0; j < contentsofx2.length; j++) {
if (contentsofx[i] == contentsofx2[j]) {
if(i<contentsofy.length && i<contentsofy2.length && contentsofy[i]==contentsofy2[j]){
System.out.println(true);
flag=false;
}
}
}
}
if(flag) {
System.out.println(false);
}
flag=true;
}
scan.close();
}
public static int[] contentsOfX(int lx, int rx) {
int[] line = new int[(rx - lx)];
for (int i = 0; i < line.length; i++) {
line[i] = lx + i;
}
return line;
}
public static int[] contentsOfY(int ly, int ry) {
int[] line = new int[(ly - ry)];
for (int i = 0; i < line.length; i++) {
line[i] = ry + i;
}
return line;
}
}
Just to make sure, you are changing "C:/Users/minda_000/Desktop/text.txt" to args[0] before uploading your solution to CodeEval, right?
Some of the other issues:
You're outputting True and False in lowercase when they're supposed to be capitalized.
In this line --
if(i<contentsofy.length && i<contentsofy2.length && contentsofy[i]==contentsofy2[j]){
-- you've got a problem when i and/or j are larger than the lengths of contentsofy and contentsofy2.
And comments would make your code easier to read. :-)
I scrapped this code and started over more or less with a much cleaner solution just using boolean logic. The problems with this code is the contentsOfX and contentsOfY methods should be 1 size greater for one point overlap. Additionally, at this time I implied one rectangle would always be to the left of the other. The nested for loop does not work as intended because of this. Still the arrays are sorted for each value from minimum value of x,y to maximum value of x,y so if you check for the reverse polarity index within the array as well the logic should be the work.

Replacing a number in an array if duplicates are found

Make the user enter 5 integer values into the array in the main method. Pass array into a separate function. There, check for duplicated values in the array. If duplicates are found, eliminate the duplicate integer and replace it with -1.
Print the processed array back in the main method.. i think i know how to replace the value with -1 but how do I return the array to the main back again. The code is:
package methods;
import java.util.*;
public class remdup {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
int [] x= new int [5];
for (int i=0; i<5; i++) {
x[i]=in.nextInt();
}
check(x);
// Insert method here
}
//Method check starts here...
public static void check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
int j = i+1;
for (i=0; i<len-1; i++) {
for (j=i+1; j<len-1;j++ ) {
if (y[i]==y[j]) {
//how to replace numbers???
y[i]=-1;
System.out.println("Duplicate found");
}
}
}
}
}
use a Set to keep track of the numbers you already have. Iterate over your array and check if the set contains the number at your current position. if yes: replace it with -1. if no: add the number to the set...
public static void check(int []y) {
Set<Integer> foundNumbers = new HashSet<Integer>();
for(int index = 0; index < y.length; index++) {
if(foundNumbers.contains(y[index]) {
y[index] = -1;
} else {
foundNumbers.add(y[index]);
}
}
}
you replace number in the array like this:
y[i] = -1;
but your check function will not work this way.
Since this is homework, I will not go into details however, if you look at your check function:
public static void check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
int j = i+1;
for (i=0; i<len-1; i++) {
if (y[i]==y[j]) {
//how to replace numbers???
System.out.println("Duplicate found");
}
}
}
You will notice that you are initially setting j to 1, but you are never updating its value. So in your for loop, you need to update the value of j at the end of each iteration.
You also need to include an extra loop, one which holds the current number and another one which checks the rest. Lastly, to overwrite the value you have, simply write to the array like so: y[i] = -1.
Change your whole like this way
import java.util.*;
public class test1 {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
int [] x= new int [5];
for (int i=0; i<5; i++) {
x[i]=in.nextInt();
}
int z[]=check(x);
for(int o=0;o<z.length;o++)
{
System.out.println(z[o]);
}
// Insert method here
}
//Method check starts here...
public static int[] check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
//int j = i+1;
for (i=0; i<len; i++) {
for(int j=0;j<i;j++)
{
if (y[i]==y[j]) {
//how to replace numbers???
y[i]=-1;
// System.out.println("Duplicate found");
}
} }
for(int k=0;k<len;k++)
{
//System.out.println(y[k]);
}
return y;
}
}
This will work for you.
public static void main(String[] args){
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
Map<Integer,Integer> map=new HashMap<>();
int [] x= new int [5];
for (int i=0; i<5; i++) {
int val=in.nextInt();
x[i]=val;
Integer iniVal=map.get(val);
if(iniVal==null){
iniVal=0;
}
map.put(val,iniVal+1);
}
int[] y=getNewArr(x,map);
for (int i=0;i<y.length;i++){
System.out.println(y[i]);
}
}
public static int[] getNewArr(int[] x,Map<Integer,Integer> map){
for(int i=0;i<x.length;i++){
int numElement=map.get(x[i]);
if(numElement!=1){
for(int j=0;j<i;j++){
if(x[i]==x[j]){
x[i]=-1;
}
}
}
}
return x;
}
input array: {1,4,5,1,2}
Output array: {1,4,5,-1,2}
Though this is a very old post I think there is an error in the accepted answer. We should be adding the replaced number back to the array. However in the accepted answer we are replacing it with -1 but we are never adding it back to SET.
Below is my corrected solution :
public static Set<Integer> check(int []y) {
Set<Integer> foundNumbers = new HashSet<Integer>();
for(int index = 0; index < y.length; index++) {
if(foundNumbers.contains(y[index])){
y[index] = -1;
}
foundNumbers.add(y[index]);
}
return foundNumbers;
}

Reverse root java

This is a problem set
This is my realization it works, but i get wrong answer on acm.timus.ru
import java.io.PrintWriter;
import java.util.Scanner;
public class SqrtBack{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int count = 0;
PrintWriter out = new PrintWriter(System.out);
long[] arr = new long[131072];
while(in.hasNextLong()){
arr[count] = in.nextLong();
count++;
}
for(int i = arr.length-1; i>=0; i--){
System.out.printf("%.4f%n", (Math.sqrt(arr[i])));
}
out.flush();
}
}
You are always printing 131072 values even though the input could be fewer... Change your loop to:
for(int i = count - 1; i >= 0; i--) ...
Note: Always try with the sample data when doing problems like this. In this case you would see the problem directly..

Categories