A riddle in java - Java - java

My friend gave me a riddle to solve. It goes like this:
There are 100 people. Each one of them, in his turn, does the following:
The first person opens all the boxes. The second person change the
state to all the boxes whose number is divided by 2, without
remainders. For instance, if a box is open and its number is divided
by 2, it is closed. The same goes for a closed box.
The third person change the state to all the boxes whose number is
divided by 3, without remainders. The "i" person change the state to
all the boxes whose number is divided by i, without remainders.
Now, at then end of the process, I need to display all the boxes(their
numbers) who are open.
I tried to implement a solution but I think it's not efficient. Here it is:
public class BoxesExc {
public static void main(String[] args) {
Box[] boxes = new Box[100];
// Inflating the array with boxes
for(int i=0; i<boxes.length; i++) {
boxes[i] = new Box(i, false);
}
// Main part:
for(int i=1; i<=boxes.length; i++) {
for(int j=1; j<=i; j++) {
// If the number is even
if(i%2 == 0) {
if(j%i == 0) {
boxes[j].setOpen(!boxes[j].isOpen);
}
}
// If the number is odd
else {
if(j%2 != 0) {
if(j%i == 0) {
boxes[j].setOpen(!boxes[j].isOpen);
}
}
}
}
}
//Displaying the opened boxes:
for(Box box : boxes) {
if(box.isOpen)
System.out.println(box.getNum()+",");
}
}
public static class Box {
private int num;
private boolean isOpen;
public Box(int num, boolean isOpen) {
this.isOpen = isOpen;
}
public int getNum() {
return num;
}
public boolean isOpen() {
return isOpen;
}
public void setOpen(boolean isOpen) {
this.isOpen = isOpen;
}
}
}
I haven't tried that yet but I just by looking at it, it looks awful.
I need your help guys with finding a better solution.
EDIT: Alright guys I managed to solve this. Here is the solution:
public class BoxesExc {
public static void main(String[] args) {
int[] boxes = new int[101];
// Inflating the array with boxes
for(int i=1; i<boxes.length; i++) {
boxes[i] = i;
}
int counter = 0;
for(int i=1; i<boxes.length; i++) {
for(int j=1; j<=i; j++) {
if(i%j == 0)
counter++;
}
if(counter%2 != 0)
System.out.print(""+i+", ");
counter = 0;
}
}
}

it has very simple solution
the boxes which will be opened will be all the boxes which thier place is square exponentiation of a number.
for example in your question its between 1-100 so the answer will be:
1 4 9 16 25 36 49 64 81 100
also my solution is faster than yours because its order is θ(√n)

Iterate through all the boxes and modulate by your current indices. Do a switch to set the box open or closed depending on it's previous state. Then after you're done doing the 100 loop; do a secondary loop through the 100 boxes to see which ones are open and print them out.

Here is a quick implementation of what I described in the comment:
public class BoxesExc {
public static void main(String[] args) {
Box[] boxes = new Box[100];
// Inflating the array with boxes
for(int i=0; i<boxes.length; i++) {
boxes[i] = new Box(i, false);
}
// Main part:
for (int i=1; i < boxes.length; i++) {
// j+=i goes 3,6,9... for i = 3
for (int j = i; j < boxes.length; j+=i) {
boxes[j].setOpen(!boxes[j].isOpen);
}
}
//Displaying the opened boxes:
for(Box box : boxes) {
if(box.isOpen)
System.out.println(box.getNum()+",");
}
}
}
Nota: you can init the box status to open and skip the first iteration (start with i = 2)

Since you only need to print the numbers, I think following is enough:
public class BoxesExc {
public static void main(String[] args) {
int boxNum = 100;
for(int i = 1; i*i <= boxNum; i++) {
System.out.print(i*i+",");
}
}
}

Related

I am working on an assignment about ordered list in java. We're not allowed to use sort so I made a solution but 2 numbers are outputted twice

here's the code for MyArrayList
public void addLast(int number){
if(!isFull())
doubleTheArray();
element[count++] = number;
}
and here's the code for MyOrderedList
public void add(int item){
for(int i = 0; i < count; i++){
for(int j = i+1; j < count; j++){
if(element[i] > element[j]){
item = element[i];
element[i] = element[j];
element[j] = item;
}
}
}
addLast(item);
}
This is the main method
public static void main(String [] args){
MyOrderedList oList = new MyOrderedList();
oList.add(3);
oList.add(5);
oList.add(2);
oList.add(4);
oList.add(7);
oList.add(8);
oList.add(10);
System.out.println("Ordered list of items: "+ oList);
}
Can anyone help me find out what's wrong? We're not allowed to use sort so I made a solution but 2 numbers are outputted twice in the main method for MyOrderedList. We have to add the elements at the right location. Or in ascending order for add(item). isFull() is boolean method that doubles (doubleTheArray()) the array size if it is true.

Number is not added at back of existing array

Learning about Arrays. I am not able to figure out why a new number is not added to the back of my existing array. I read in two textfiles in file_1.txt are the numbers '1 2 3' and in file_2.txt is the number '91'. Basically without the method of Void addBack() the program does what I expect, however by adding the method it seems not make a new Array. Even when I go over the elements[i] = elements[i-1] it won't print it as a whole. I am expecting to print for the first part
The numbers are: 1 2 3 and the second part The numbers are: 1 2 3 91.
public class ExampleLecture {
IntRow readIntRow(Scanner input) {
IntRow result = new IntRow();
while (input.hasNext()) {
result.add(input.nextInt());
}
return result;
}
IntRow setBack(Scanner input) {
IntRow result = new IntRow();
while(input.hasNext()) {
result.addBack(input.nextInt());
System.out.println("here");
}
return result;
}
void print(IntRow row) {
for (int i = 0; i < row.numberOfElements; i++) {
System.out.printf("%d ", row.elements[i]);
}
System.out.printf("\n");
}
void start() {
Scanner in = UIAuxiliaryMethods.askUserForInput().getScanner();
Scanner in2 =UIAuxiliaryMethods.askUserForInput().getScanner();
IntRow row = readIntRow(in);
IntRow row2 = setBack(in2);
System.out.printf("the numbers are: ");
print (row);
System.out.printf("the new numbers are: ");
print (row2);
}
public static void main(String[] args) {
new ExampleLecture().start();
}
}
package examplelecture;
class IntRow {
static final int MAX_NUMBER_OF_ELEMENTS = 250;
int[] elements;
int numberOfElements;
IntRow() {
elements = new int[MAX_NUMBER_OF_ELEMENTS];
numberOfElements = 0;
}
void add(int number) {
elements[numberOfElements] = number;
numberOfElements += 1;
}
void addBack(int number) {
for (int i = numberOfElements; i>0; i--) {
elements[i] = elements[i-1];
elements[i] = number;
}
}
}
You have 2 successive assignments which write to the same position:
elements[i] = elements[i-1];
elements[i] = number;
The value is alway overwritten with number, so the first statement has no effect.
Also in your addBack method your for cycle:
for (int i = numberOfElements; i>0; i--) {
What happens if numberOfElements is 0?
You call it addBack but it looks like a better name for the method is addFirst. Usually index 0 is considered the front, not the back.
First off, both the readIntRow() and setBack() methods create new IntRow objects row and row2. If you want the result to be appended to the first IntRow object created i.e. to row , you should call:
IntRow row = readIntRow(in);
IntRow row2 = row.setBack(in2);
and setBack() needs to be modified to:
IntRow setBack(Scanner input) {
while(input.hasNext()) {
this.add(input.nextInt());
System.out.println("here");
}
return this;
}
Note that in setBack(), if you are trying to append numbers to the end of the IntRow object, you should call add() instead of addBack() as above. If you are trying to add to the front, you should call addBack() [and it might be better to call it addFront() instead].
Also, in the implementation of addBack(), if you are trying to add to the front of the IntRow object, the element[i] = number operation should take place only once, after the loop. Otherwise all the values in indices <= numberOfElements would be overwritten with number.
void addBack(int number) {
for (int i = numberOfElements; i>0; i--) {
elements[i] = elements[i-1];
}
elements[0] = number;
}
Admittedly it is not entirely clear what you are trying to accomplish. But you may have several problems. The first is as follows:
IntRow setBack(Scanner input) {
IntRow result = new IntRow();
while (input.hasNext()) {
result.addBack(input.nextInt());
System.out.println("here");
}
return result;
}
IntRow has nothing in it since it is new. So all you are doing is iterating over the new file which has just 91 in it. Remember, result has no items. So it won't even iterate once in addBack.
So just do the following:
Change your addBack method to just add the numbers. Why use a loop to cascade down the elements since you are doing this within the same instance of IntRow? Just add it on to the end using the numberofElements as the next index.
void addBack(int number) {
elements[numberOfElements++] = number;
}
If you want to copy the contents of one IntRow object to another you would need another method in the IntRow class. Something like:
public void copy(IntRow r) {
for (int i = 0; i < r.numerOfElements; i++) {
elements[i] = r.elements[i];
}
numerOfElements = r.numberOfElements;
}
And keeping with good design it might be better to return numberOfElements in a method such as public int size();

How do I save an output from a method to use it in a different method?

Im sorry if this question has been asked a lot. Im still pretty new to programming and obviously have some issues in phrasing questions/searching for answers.
I want to do the following:
My algorithm includes 2 methods. One has the task to find out how many of the numbers between 0 to 30 are even and which one are not. I want those even numbers to be somehow stored and redirected to my second method to get added. How can I store those even numbers?
My code looks currently like this: (not even close to being finished)
public class Add
{
static long method(long end)
{
long number = even;
return;
}
static long even() {
if (i%2 == 0) { // even
}
else { // uneven
}
}
public static void main(String[ ] args)
{
int number = method(30);
System.out.println("");
}
}
edit:Im having formating problems... Im sorry the code looks even harder to understand. Im trying to fix it this instant.
Like it was said in the comments, add them to a list, then iterate the list while updating a variable that will be the sum of the even numbers.
public class Add {
private static ArrayList<Integer> evenNums = new ArrayList<>();
private static void evenNumbers(int max) {
for (int i = 0; i < max; i++) {
if (i % 2 == 0) {
evenNums.add(i);
}
}
}
private static int sum(ArrayList<Integer> array){
int sum = 0;
for(int i = 0; i < array.size(); i++){
sum = sum + i;
}
return sum;
}
public static void main (String[]args){
evenNumbers(30);
int sum = sum(evenNums);
System.out.println(sum);
}
}

Reading data from Csv File

How to find sequence of missing number from a CSV file using java Program?
I was using Arraylist taking some numbers into consideration.
I want to read entire CSV file Data And find the missing sequences on numbers.I have near about 1,00,000 records in the file.
Program:-
public class MissingNumber {
public static long count = 0;
public static int position = 0;
public static boolean flag = false;
public static void main(String[] args) {
long a[] = {1054023,1054024,1054025,1054026,1054027,1054028,1054029,1054030,1054031,1054032,1054748,1054749,1054750,1054751,
1054752,1054753,1054754,1054755,1054756,1054757,1054758,1055297,1055298,1055299,1055300,1055301,1055302,1055303,1055304,
1055305,1055306,1055307,1055308,1055309,1056868,1057170,1057461,1057563,1057627,1057628,1057629,1057630,1057631,1057632,
1057633,1057634,1057635,1057636,1057637,1057652,1057653,1057654,1057656,1057657,1057661,1057662,1057663,1057664,1057665,
1057672,1057673,1057674,1057675,1057678,1057682,1057683,1057685,1057686,1057687,1057690,1057691,1057692,1057695,1057696,
1057697,1057698,1057699,1057701,1057702,1057705,1057706,1057707,1057708,1057710,1057712,1057718,1057722,1057729,1057730,
1057731,1057732,1057733,1057734,1057735,1057736,1057738,1057739,1057740,1057741,1057742,1057743,1057744,1057745,1057746,
1057747,1057748,1057749,1057750,1057751,1057752,1057753,1057754,1057755,1057756,1057757,1057758,1057759,1057762,1057763,
1057764,1057765,1057766,1057767,1057768,1057769,1057773,1057774,1057778,1057779,1057780,1057781,1057782,1057783,1057784,
1057785,1057786,1057787,1057788,1057789,1057790,1057791,1057792,1057793,1057794,1057795,1057796,1057797,1057798,1057799,
1057800,1057801,1057802,1057803,1057804,1057805,1057806,1057807,1057808,1057809,1057810,1057811,1057825,1057826,1057827,
1057829,1057838,1057843,1057857,1057858,1057859,1057860,1057861,1057862,1057863,1057864,1057865,1057866,1057867,1057868,
1057869,1057870,1057871,1057872,1057873,1057874,1057875,1057876,1057884,1057885,1057886,1057887,1057888,1057889,1057890,
1057891,1057892,1057893,1057894,1057895,1057896,1057897,1057898,1057899,1057900,1057901,1057902,1057903,1057905,1057906,
1057907,1057908,1057909,1057910,1057911,1057912,1057913,1057914,1057915,1057916,1057917,1057918,1057919,1057920,1057921};
findMissingNumbers(a, position);
}
private static void findMissingNumbers(long a[], int position) {
if (position == a.length - 1)
return;
for (; position < a[a.length - 1]; position++) {
if ((a[position] - count) != position)
{
System.out.println("position"+position);
System.out.println("Missing Number: " + (position + count));
flag = true;
count++;
break;
}
}
if (flag) {
flag = false;
findMissingNumbers(a, position);
}
}
}
I assume your array is already sorted. If so itreate through and find the missing nrs like you were doing it manually; compare two neighbors and if the difference is more than one print the numbers missing. something like this:
public class MissingNumber {
public static void main(String[] args) {
long a[] = {1,2,3,5,9,11,23,24,25,26,27,28,39}; //try first on small arrays
findMissingNumbers(a);
}
private static void findMissingNumbers(long a[]) {
for(int i = 0; i<a.length-1; i++){
if(a[i+1]- a[i] > 1){
System.out.println("missing nr at index: " + (i+1));
System.out.println("missing nrs");
for (int j = 1;j<a[i+1]-a[i];j++){ // for ex. if a[i] = 13 and a[i+1]= 17 difference is 4 and there are 3 missing nrs.
System.out.println(a[i]+j);
}
}
}
}
}
And to easily read from csv file i recomend opencsv

Java Bot saves Princess Challenge

Princess Peach is trapped in one of the four corners of a square grid. You are in the center of the grid and can move one step at a time in any of the four directions. Can you rescue the princess?
Input format
The first line contains an odd integer N (3 <= N < 100) denoting the size of the grid. This is followed by an NxN grid. Each cell is denoted by '-' (ascii value: 45). The bot position is denoted by 'm' and the princess position is denoted by 'p'.
Grid is indexed using Matrix Convention
Output format
Print out the moves you will take to rescue the princess in one go. The moves must be separated by '\n', a newline. The valid moves are LEFT or RIGHT or UP or DOWN.
Here is my code:
package challenges;
import java.util.*;
public class Solution {
static void displayPathtoPrincess(int n, int p,String [][] grid){
int botRow=0,botCol=0;
for(int r=0;r<n;r++){
for (int c = 0; c < grid.length; c++) {
if(grid[r][c].equals('m')) {
botRow=r;
botCol=c;
continue;
}
}
if(grid[0][0].equals('P')) {
while(botRow>0) {
botRow--;
System.out.println("UP\n");
}
while(botCol>0) {
botCol--;
System.out.println("LEFT\n");
}
}
else if(grid[0][p-1].equals('P')) {
while(botRow>0) {
System.out.println("UP\n");
botRow--;
}
while(botCol<p-1) {
botCol++;
System.out.println("RIGHT\n");
}
}
else if(grid[n-1][0].equals('P')) {
while(botRow<n-1) {
botRow++;
System.out.println("DOWN\n");
}
while(botCol>0) {
botCol--;
System.out.println("LEFT\n");
}
}
else if(grid[n-1][p-1].equals('P')) {
while(botRow<n-1) {
botRow++;
System.out.println("DOWN\n");
}
while(botCol<p-1) {
botCol++;
System.out.println("RIGHT\n");
}
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m,n;
m = in.nextInt();
n=m;
int j=0;
String grid[][] = new String[m][n];
for(int i = 0; i < m; i++) {
while(j<n){
grid[i][j] = in.next();
j++;
}
}
displayPathtoPrincess(m,n,grid);
}
}
Its giving Null Pointer Exception.can anyone please tel what am i doing wrong in here?
Try this solution:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Solution
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int m = Integer.parseInt(br.readLine());
char grid[][] = new char[m][m];
for(int i = 0; i < m; i++)
{
String line = br.readLine();
grid[i] = (line.trim()).toCharArray();
}
displayPathtoPrincess(m, grid);
}
static void displayPathtoPrincess(int m, char[][] grid)
{
int botRow = 0, botCol = 0, princessRow = 0, princessCol = 0;
// Get bot and princess coordinates
for (int r = 0; r < m; r++)
{
for (int c = 0; c < grid.length; c++)
{
if (grid[r][c] == 'm' || grid[r][c] == 'M')
{
botRow = r;
botCol = c;
}
else if (grid[r][c] == 'p' || grid[r][c] == 'P')
{
princessRow = r;
princessCol = c;
}
}
}
// Move the bot up or down till bot reaches same row
if( princessRow < botRow )
{
while(botRow != princessRow)
{
botRow--;
System.out.println("UP");
}
}
else if( princessRow > botRow )
{
while(botRow != princessRow)
{
botRow++;
System.out.println("DOWN");
}
}
// Move the bot left or right till bot reaches same column
if( princessCol < botCol )
{
while(botCol != princessCol)
{
botCol--;
System.out.println("LEFT");
}
}
else if( princessCol > botCol )
{
while(botCol != princessCol)
{
botCol++;
System.out.println("RIGHT");
}
}
}
}
Ok, no offence but this code is a mess.
I know what I will answer won't be exactly what you want, but it might be very helpful for you in the future.
What would I change? (After you change all of this, the error will more likely become apparent or it will be clear enough to ask for help)
First: Variable types.
This is just a tiny detail, but I don't like the way you did it; why use a String if every cell will be represented by a char?
Every time you create a variable (or an Array, or anything at all) think about what you need it to store, and create the variable in a way it will store what you need. If you needed it to store if something is true or false, you wouldn't create a String variable and store "true" or "false", you would use a boolean.
Apply this every time and you will improve faster.
Second: use functions.
Functions are a great way to abstract yourself from the implementation details.
I mean, you can easily see the difference between something like your code, and something like:
static void displayPathtoPrincess(int n, int p,char [][] grid){
Point bot;
Point princess;
getInitialPositions(bot, princess, grid);
Point dif = getRelativePrincessPosition(bot, princess);
while (!bot.equals(princess)) {
switch (dif.y) {
case UP:
move (UP_MOVEMENT);
break;
case DOWN:
move (DOWN_MOVEMENT);
break;
}
switch (dif.x) {
case LEFT:
move(LEFT_MOVEMENT);
break;
case RIGHT:
move(RIGHT_MOVEMENT);
break;
}
}
}
(And then implement the necessary methods, and create the constants, that is something pretty easy to do)
Third: use the appropriate loop every time.
If you know you want to go from j = 0, while j < n, increasing j every iteration; that's not called a while, that's called a for. (Also, as someone else commented in their answer, you forgot to restart the j; so it only goes in once.
Finally: Let's go with your error now.
I believe your code might be pretty buggy and not give you the desired output, but the NullPointerException is something more specific.
Since you don't use the appropriate loop in the main, for j, and you forgot to restart it's value, you didn't fill the whole array.
When you try to read a value you didn't fill (in the for where you find the robot's position), that value is null, and the value for some rows will be null too; hence the NullPointerException (because you try to access the value of a null array).
While taking input you have to make j =0 every time you are coming out of while loop as
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m,n;
m = in.nextInt();
n=m;
int j=0;
String grid[][] = new String[m][n];
for(int i = 0; i < m; i++) {
j = 0;
while(j<n){
grid[i][j] = in.next();
j++;
}
}
i remains 0 due to this mistake.
You should put print statement to check why are you getting error.
here is the solution..
import java.util.*;
public class Solution {
static void displayPathtoPrincess(int n, int p, String[][] grid) {
int botRow = 0, botCol = 0;
for (int r = 0; r < n; r++) {
for (int c = 0; c < grid.length; c++) {
if (grid[r][c].equalsIgnoreCase("m")) {
botRow = r;
botCol = c;
}
}
if (grid[0][0].equalsIgnoreCase("P")) {
while (botRow > 0) {
botRow--;
System.out.println("UP\n");
}
while (botCol > 0) {
botCol--;
System.out.println("LEFT\n");
}
} else if (grid[0][p - 1].equalsIgnoreCase("P")) {
while (botRow > 0) {
botRow--;
System.out.println("UP\n");
}
while (botCol < p - 2) {
botCol++;
System.out.println("RIGHT\n");
}
} else if (grid[n - 1][0].equalsIgnoreCase("P")) {
while (botRow < n - 2) {
botRow++;
System.out.println("DOWN\n");
}
while (botCol > 0) {
botCol--;
System.out.println("LEFT\n");
}
} else if (grid[n - 1][p - 1].equalsIgnoreCase("P")) {
while (botRow < n - 2) {
botRow++;
System.out.println("DOWN\n");
}
while (botCol < p - 2) {
botCol++;
System.out.println("RIGHT\n");
}
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m,n;
m = in.nextInt();
int j;
String grid[][] = new String[m][m];
for(int i = 0; i < m; i++) {
for(j=0;j<m;j++){
grid[i][j] = in.next();
}
}
displayPathtoPrincess(m,m,grid);
}
}
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static void nextMove(int n, int r, int c, String [] grid){
int xcord=0;
int ycord=0;
for ( int i = 0 ; i <n-1; i++){
String s = grid[i];
xcord=i;
for(int x =0; x<=n-1;x++){
if(s.charAt(x)=='p'){
ycord=x;
if(xcord==r){
if(ycord>c){System.out.println("RIGHT");return;}
else {System.out.println("LEFT");return;}
}else if(xcord<r){System.out.println("UP");return;}
else{ System.out.println("DOWN");return;}
}
}
}
System.out.println(xcord);
System.out.println(ycord);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n,r,c;
n = in.nextInt();
r = in.nextInt();
c = in.nextInt();
in.useDelimiter("\n");
String grid[] = new String[n];
for(int i = 0; i < n; i++) {
grid[i] = in.next();
}
nextMove(n,r,c,grid);
}
}
You might wish to take a look at the following code in Java:
import java.util.Scanner;
public class Solution {
/*
*
*/
static void printPath(int n, String moves) {
for (int i = n / 2; i >= 0; i -= 2) {
System.out.println(moves);
}
}
/*
*
*/
static void displayPathtoPrincess(int n, String [] grid){
// **** princess # top left ****
if (grid[0].substring(0, 1).equals("p")) {
printPath(n, "UP\nLEFT");
}
// **** princess # top right ****
else if (grid[0].substring(n - 1, n).equals("p") ) {
printPath(n, "UP\nRIGHT");
}
// **** princess # bottom right ****
else if (grid[n - 1].substring(n - 1, n).equals("p")) {
printPath(n, "DOWN\nRIGHT");
}
// **** princess # bottom left ****
else {
printPath(n, "DOWN\nLEFT");
}
}
/*
* Test code
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m;
m = in.nextInt();
String grid[] = new String[m];
for(int i = 0; i < m; i++) {
grid[i] = in.next();
}
// **** ****
in.close();
// **** ****
displayPathtoPrincess(m,grid);
}
}

Categories

Resources