The following is the java code. I am trying to get the arrays from the problem1.txt and save it into the arraylist.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
class CSP {
public int nMeetings;
public static int nEmployees;
public int nTimeSlots;
public static int probNumber;
public ArrayList<ArrayList<Integer>> nMeetingsPerEmployee;
//public int[][] travelTime;
public CSP(int nMeetings, int nEmployees, int nTimeSlots, int probNumber) throws FileNotFoundException {
this.nMeetings = nMeetings;
this.nEmployees = nEmployees;
this.nTimeSlots = nTimeSlots;
this.probNumber = probNumber;
this.nMeetingsPerEmployee = getnMeetingsPerEmployeeArrayList();
}
//gets nMeetingsPerEmployee Arrylist
public static ArrayList<ArrayList<Integer>> getnMeetingsPerEmployeeArrayList() throws FileNotFoundException
{
ArrayList<ArrayList<Integer>> arraylist = new ArrayList<ArrayList<Integer>>();
File openFile = null;
if(probNumber == 1){
openFile = new File("problem1.txt");
}else if(probNumber == 2){
openFile = new File("problem2.txt");
}else if(probNumber ==3){
openFile = new File("problem3.txt");
}else
System.out.println("File Not Found");
Scanner in = new Scanner(openFile);
for(int i=0; i<5; i++)
in.nextLine(); //skip 5 lines until matrix
while(true){
for(int i=0; i<nEmployees; i++) //nEmployees = 33
{
for(int j=0; j<6 ;j++)
{
for(int k=0; k<3; k++)
in.next(); //skip 3 characters until individual number
arraylist.get(nEmployees).set(nEmployees, Integer.parseInt(in.next()));
if(in.hasNext() == false);
break;
}
}
return arraylist;
}
}
}
public class CSP_Main
{
public static void main(String[] args) throws FileNotFoundException
{
CSP problem1 = new CSP(20, 33, 12, 1);
//CSP problem2 = new CSP(20, 33, 12, 2);
//CSP problem3 = new CSP(40, 62, 12, 3);
}
}
The following is the error I keep getting.
Exception in thread "main" java.io.FileNotFoundException: problem1.txt
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at CSP.getnMeetingsPerEmployeeArrayList(CSP_Main.java:43)
at CSP.<init>(CSP_Main.java:22)
at CSP_Main.main(CSP_Main.java:70)
The following is the problem1.txt file that I am trying to read and save in the arraylist.
Number of meetings: 20
Number of employees: 33
Number of time slots: 12
Meetings each employee must attend:
1: 2 6 7 9 19
2: 2 5 6 12 16
3: 1 3 8 9 16
4: 1 6 15 16 18
5: 1 3 8 13 18
6: 8 10 11 17 20
7: 3 8 10 13 20
8: 1 3 14 16 20
9: 6 7 9 16 19
10: 2 6 7 12 17 19
11: 2 6 7 9 13
12: 2 4 7 12 16
13: 2 6 7 9 16 18
14: 2 5 11 17 18
15: 1 5 11 17 18 20
16: 6 8 12 16 18
17: 6 7 15 17 19
18: 1 7 11 18 20
19: 4 5 9 10 13
20: 4 7 9 17 18
21: 7 10 11 12 17
22: 5 6 9 13 18
23: 1 9 11 17 18
24: 2 11 14 15 17
25: 1 3 14 15 16
26: 5 6 10 13 15
27: 8 11 15 17 18
28: 1 4 7 9 16
29: 1 11 13 18 20
30: 2 5 12 13 18
31: 2 6 8 12 16
32: 2 7 15 17 19
33: 6 7 15 17 18
Travel time between meetings:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1: 0 1 1 1 2 1 1 1 1 1 1 2 1 2 1 1 1 1 2 1
2: 1 0 1 1 2 2 1 1 1 1 1 1 1 1 1 2 2 1 1 2
3: 1 1 0 1 1 2 2 1 1 2 2 2 2 2 2 1 2 2 1 1
4: 1 1 1 0 1 2 2 2 2 2 1 1 1 2 2 1 1 2 2 2
5: 2 2 1 1 0 2 2 2 1 1 1 2 1 2 1 2 2 1 2 2
6: 1 2 2 2 2 0 1 1 1 1 2 1 2 1 2 1 1 2 2 1
7: 1 1 2 2 2 1 0 1 2 1 1 1 1 1 2 2 2 1 1 2
8: 1 1 1 2 2 1 1 0 2 1 1 2 1 1 2 1 2 1 2 1
9: 1 1 1 2 1 1 2 2 0 2 2 1 1 1 2 2 2 2 1 2
10: 1 1 2 2 1 1 1 1 2 0 1 2 2 2 2 2 1 1 2 2
11: 1 1 2 1 1 2 1 1 2 1 0 1 2 1 1 2 1 2 1 1
12: 2 1 2 1 2 1 1 2 1 2 1 0 1 2 2 2 2 1 2 2
13: 1 1 2 1 1 2 1 1 1 2 2 1 0 1 1 2 2 2 1 1
14: 2 1 2 2 2 1 1 1 1 2 1 2 1 0 2 1 1 2 1 1
15: 1 1 2 2 1 2 2 2 2 2 1 2 1 2 0 2 1 2 2 1
16: 1 2 1 1 2 1 2 1 2 2 2 2 2 1 2 0 1 1 2 2
17: 1 2 2 1 2 1 2 2 2 1 1 2 2 1 1 1 0 2 2 2
18: 1 1 2 2 1 2 1 1 2 1 2 1 2 2 2 1 2 0 1 1
19: 2 1 1 2 2 2 1 2 1 2 1 2 1 1 2 2 2 1 0 2
20: 1 2 1 2 2 1 2 1 2 2 1 2 1 1 1 2 2 1 2 0
The problem1.txt file that I am trying to open is surely in the directory where my java codes are. So I don't know why I keep getting this error.
Thank you for your time.
ProjectRoot is working directory for Eclipse.
Move file above src directory i.e. to project root (Running from eclipse)
openFile = new File("problem1.txt");
Provide path from src or bin to file location (Running from eclipse):
openFile = new File("src/superbase/problem1.txt");
You can see the bellow example.You will get file from same package.
public class Hello {
public static void main(String[] args) {
Hello obj = new Hello();
System.out.println(obj.getFile("file/p1.txt"));
}
private String getFile(String fileName) {
StringBuilder result = new StringBuilder("");
//Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
result.append(line).append("\n");
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
}
This exception will is thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname does not exist. It is also thrown by these constructors if the file does exist but for some reason is inaccessible, for example when an attempt is made to open a read-only file for writing.
For more Information : https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html
This is how you can give correct path you did not add backslash and also backslash should be two because one backslash is consider as escape sequence.
File file = File("C:\\abcfolder\\textfile.txt");
Related
So I have edited it some and am getting almost exactly what I want. The only problem I am having now is that I am getting a line of output that I don't want. I feel like the fix here is simple but my brain is fried right now.
static void bubbleSort(int[] myArray) {
int n = myArray.length;
int temp = 0;
int counter = 0;
for (int i = 0; i < n; i++) {
int k;
for (k = 0; k < n; k++) {
System.out.print(myArray[k] + "|");
}
System.out.println(" Num swaps: " + counter);
for (int j = 1; j < (n - i); j++) {
if (myArray[j - 1] > myArray[j]) {
//swap elements
temp = myArray[j - 1];
myArray[j - 1] = myArray[j];
myArray[j] = temp;
counter++;
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] myArray = new int[10];
for (int i = 0; i < 10; i++) {
System.out.print("Enter slot " + i + ": ");
myArray[i] = sc.nextInt();
}
bubbleSort(myArray);
}
Here is an example of what I get:
Enter slot 0: 10
Enter slot 1: 9
Enter slot 2: 8
Enter slot 3: 7
Enter slot 4: 6
Enter slot 5: 5
Enter slot 6: 4
Enter slot 7: 3
Enter slot 8: 2
Enter slot 9: 1
10|9|8|7|6|5|4|3|2|1| Num swaps: 0
9|8|7|6|5|4|3|2|1|10| Num swaps: 9
8|7|6|5|4|3|2|1|9|10| Num swaps: 17
7|6|5|4|3|2|1|8|9|10| Num swaps: 24
6|5|4|3|2|1|7|8|9|10| Num swaps: 30
5|4|3|2|1|6|7|8|9|10| Num swaps: 35
4|3|2|1|5|6|7|8|9|10| Num swaps: 39
3|2|1|4|5|6|7|8|9|10| Num swaps: 42
2|1|3|4|5|6|7|8|9|10| Num swaps: 44
1|2|3|4|5|6|7|8|9|10| Num swaps: 45
That first line of output where it just repeats what the user input and says 0 swaps. I don't want that.
Just changed the position of the for loops. Hope this is the output you actually want :).
static void bubbleSort(int[] myArray) {
int n = myArray.length;
int temp = 0;
int counter = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (myArray[j - 1] > myArray[j]) {
// swap elements
temp = myArray[j - 1];
myArray[j - 1] = myArray[j];
myArray[j] = temp;
counter++;
}
}
int k;
for (k = 0; k < n; k++) {
System.out.print(myArray[k] + "|");
}
System.out.println(" Num swaps: " + counter);
}
}
Algorithm with two nested streams: Bubble sort with step-by-step output Java 8
Bubble sort with step-by-step output
The outer do-while-loop repeats until the array is sorted, and the inner for-loop passes through the array, swapping the unordered adjacent elements. The output is the swapped elements in the inner loop, grouped by passes in the outer loop.
public static void main(String[] args) {
int[] arr = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
bubbleSort(arr);
}
public static void bubbleSort(int[] arr) {
// counters
int passes = 0, swaps = 0;
// marker
boolean swapped;
// repeat the passes through the array until
// all the elements are in the correct order
do {
// output the beginning of the pass and increase the counter of passes
System.out.print((passes == 0 ? "<pre>" : "<br>") + "Pass: " + passes++);
swapped = false;
// pass through the array and
// compare adjacent elements
for (int i = 0; i < arr.length - 1; i++) {
// if this element is greater than
// the next one, then swap them
if (arr[i] > arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
// output the array and increase the counter of swaps
System.out.print(outputSwapped(arr, i, i + 1, swaps++));
}
}
// if there are no swapped elements at the
// current pass, then this is the last pass
} while (swapped);
// output total
System.out.print("<br>Total: Passes=" + passes);
System.out.println(", swaps=" + swaps + "</pre>");
}
static String outputSwapped(int[] arr, int e1, int e2, int counter) {
StringBuilder sb = new StringBuilder("<br>");
for (int i = 0; i < arr.length; i++) {
if (i == e1 || i == e2) {
// swapped elements are in bold
sb.append("<b>").append(arr[i]).append("</b>");
} else {
// other elements
sb.append(arr[i]);
}
sb.append(" ");
}
return sb.append("| ").append(counter).toString();
}
Output:
Pass: 09 10 8 7 6 5 4 3 2 1 | 09 8 10 7 6 5 4 3 2 1 | 19 8 7 10 6 5 4 3 2 1 | 29 8 7 6 10 5 4 3 2 1 | 39 8 7 6 5 10 4 3 2 1 | 49 8 7 6 5 4 10 3 2 1 | 59 8 7 6 5 4 3 10 2 1 | 69 8 7 6 5 4 3 2 10 1 | 79 8 7 6 5 4 3 2 1 10 | 8Pass: 18 9 7 6 5 4 3 2 1 10 | 98 7 9 6 5 4 3 2 1 10 | 108 7 6 9 5 4 3 2 1 10 | 118 7 6 5 9 4 3 2 1 10 | 128 7 6 5 4 9 3 2 1 10 | 138 7 6 5 4 3 9 2 1 10 | 148 7 6 5 4 3 2 9 1 10 | 158 7 6 5 4 3 2 1 9 10 | 16Pass: 27 8 6 5 4 3 2 1 9 10 | 177 6 8 5 4 3 2 1 9 10 | 187 6 5 8 4 3 2 1 9 10 | 197 6 5 4 8 3 2 1 9 10 | 207 6 5 4 3 8 2 1 9 10 | 217 6 5 4 3 2 8 1 9 10 | 227 6 5 4 3 2 1 8 9 10 | 23Pass: 36 7 5 4 3 2 1 8 9 10 | 246 5 7 4 3 2 1 8 9 10 | 256 5 4 7 3 2 1 8 9 10 | 266 5 4 3 7 2 1 8 9 10 | 276 5 4 3 2 7 1 8 9 10 | 286 5 4 3 2 1 7 8 9 10 | 29Pass: 45 6 4 3 2 1 7 8 9 10 | 305 4 6 3 2 1 7 8 9 10 | 315 4 3 6 2 1 7 8 9 10 | 325 4 3 2 6 1 7 8 9 10 | 335 4 3 2 1 6 7 8 9 10 | 34Pass: 54 5 3 2 1 6 7 8 9 10 | 354 3 5 2 1 6 7 8 9 10 | 364 3 2 5 1 6 7 8 9 10 | 374 3 2 1 5 6 7 8 9 10 | 38Pass: 63 4 2 1 5 6 7 8 9 10 | 393 2 4 1 5 6 7 8 9 10 | 403 2 1 4 5 6 7 8 9 10 | 41Pass: 72 3 1 4 5 6 7 8 9 10 | 422 1 3 4 5 6 7 8 9 10 | 43Pass: 81 2 3 4 5 6 7 8 9 10 | 44Pass: 9Total: Passes=10, swaps=45
See also: Bubble sort output is incorrect
My purpose is a java app that takes a number from a user. Start 1 and write it to console. Each new line series will increase 1 until the number token from the user. The important thing is to align each line to the right side.
Scanner in = new Scanner(System.in);
int numberOfLines = in.nextInt();
for (int rows = 1; rows <= numberOfLines; rows++) {
for (int i = numberOfLines - rows; i >= 1; i--) {
System.out.print(" ");
}
for (int col = rows; col >= 1; col--) {
System.out.printf(" %d",col);
}
System.out.println();
}
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
when reaching double-digit numbers it is not right-aligned text. I tried to use the if condition in the loop but I could not do it.
Here's a different way to think about it using String concatenation.
You could generate the last row, first, to determine the maximum width that each row must be. Then for each row, you count backwards from the current row number down to 1 so you know the width of just the numbers part. Finally, you prepend the number of spaces needed to make the current row as wide as the last row. Note that is a horribly inefficient use of Strings, but really I'm demonstrating a different algorithm. Making this memory efficient would just make it harder to understand. Also note that the output being rendered correctly is dependent upon the environment in which you are running, and how it displays long strings. Some systems will add a scrollbar, while others may cause the strings to wrap.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Number of rows? ");
int numberOfLines = in.nextInt();
if (numberOfLines >= 1) {
int totalWidth = 0;
// add up the widths of the numbers themselves
for (int number = 1; number <= numberOfLines; number++) {
totalWidth = totalWidth + ("" + number).length();
}
// add in the spaces in-between the numbers
totalWidth = totalWidth + (numberOfLines - 1);
// now generate each row by counting backwards from the current row number
for (int rowNumber = 1; rowNumber<=numberOfLines; rowNumber++) {
String row = "";
for (int i=rowNumber; i>=2; i--) {
row = row + i + " ";
}
row = row + "1";
// prepend the spaces in front to make it as wide as the last row
int paddingLength = totalWidth - row.length();
for(int i=1; i<=paddingLength; i++) {
row = " " + row;
}
// output the row
System.out.println(row);
}
}
else {
System.out.println("Number of rows must be positive!");
}
}
Sample output with 25 rows:
Number of rows? 25
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
12 11 10 9 8 7 6 5 4 3 2 1
13 12 11 10 9 8 7 6 5 4 3 2 1
14 13 12 11 10 9 8 7 6 5 4 3 2 1
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
Your code is doing the job just fine. The one problem you have, is that it stops working properly once you get to numbers that are more than 1 digit large: In your example, the 10 and the 11.
It's actually kind of tricky to fix that - what if I input '120392'?
You have a few options. Each option is more amazing, but also requires more code.
Restrict your input. For example, disallow inputs beyond 99, and assume all numbers have a # of digits equal to the largest allowing numbers (so, 2 digits).
Calculate the # of digits in the input, then assume all numbers have the calculated # of digits.
Just get it right, with the spacing being applied increasing as numbers grow digits.
If you choose the first or second option, you'd get something like:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
Note how this has way more spaces than your example (2 spaces in between e.g. every 4 and 3 instead of 1.
So, how? For #1 and #2, you need System.out.printf("%2d"); - this means: print a number, but if it takes fewer than 2 characters to do so, left-pad with spaces.
For #1 you hardcode the '2' (and hardcode a 99 limit; alternatively, hardcode 3 spaces, and a 999 limit). For #2 you get your input and then figure out how many digits that is. Something like String.valueOf(limit).length(); will do that, then you construct the format string using this length.
For #3 you track which number you're not printing in your System.out.print(" "); loop, so that you can still figure out how long the blank space you need to make has to be: If you're not printing a 10, you need 3 spaces. If you're not printing a 500, you'd need 4. If you're not printing a 5, you need 2.
For #2 and #3: printf("%4s", ""); prints 4 spaces. This is what you'd use to ask java to print X number of spaces. You're going to need this for solutions #2 and #3.
This sounds like first-week homework. I think #1 is most appropriate.
In order to make the 2 digits right aligned ,one of the ways would be- after the for loop of 'col' convert each digit to String then reverse it then after that print it . If u don't convert it to String then numbers like 10,20,30,etc would be printed as 1,2,3,etc
for (int rows = 1; rows <= numberOfLines; rows++) {
for (int i = numberOfLines - rows; i >= 1; i--) {
System.out.print(" ");
}
for (int col = rows; col >= 1; col--) {
if(col>9){
COL=Integer.toString(col);
for(int i=COL.length();i>=0;i--)
rev=rev+COL.charAt(i);
System.out.printf(" %d",rev);
}
else
System.out.printf("%d",col);
}
System.out.println();
}
Problem : print all +ve integer solution of the equation
a^3 + b^3 = c^3 + d^3
where a, b, c, d are integers bw 1 to 1000
Facing issue with Math.pow() function.
So I have written two code one is brute force and another one with a little optimisation.
The first one is showing correct output while the 2nd one is not and this is due to the power function.
Math.pow(0,1/3) = 1 while it should be 0
class Find_a3_b3__c3_d3{
// final static int n = 100;
// solution 1 : BRUTE FORCE
public static void bruteForce(){ // O(N^4)
int n = 5;
int resultCount = 0;
for(int a=0; a<n ; a++){
for(int b=0; b<n; b++){
for(int c=0; c<n; c++){
for(int d=0; d<n; d++){
int a_3 = a*a*a;
int b_3 = b*b*b;
int c_3 = c*c*c;
int d_3 = d*d*d;
if(a_3 + b_3 == c_3 + d_3){
System.out.println((resultCount++) + " a: "+a +" b: "+b + " --- c: "+c + " d: "+d );
break;
}
}
}
}
}
System.out.println("\n\n");
}
// solution 2 : BRUTE FORCE
// idea is : as we know d is going to have one value for each pair of a,b & c so
// if we know a b & c , then we can find d by the relation cubeRoot (a_3 + b_3 - c_3);
public static void littleBetter(){ // O(N^4)
int n = 5;
int resultCount = 0;
for(int a=0; a<n ; a++){
for(int b=0; b<n; b++){
for(int c=0; c<n; c++){
int a_3 = a*a*a;
int b_3 = b*b*b;
int c_3 = c*c*c;
System.out.println(a +" " + b+" " + c +" ");
System.out.println(a_3 +" " + b_3+" " + c_3 +" " + Math.pow(a_3 + b_3 - c_3, 1/3));
int d = (int) Math.pow(a_3 + b_3 - c_3, 1/3);
int d_3 = d*d*d;
if(a_3 + b_3 == c_3 + d_3){
System.out.println((resultCount++) + " a: "+a +" b: "+b + " --- c: "+c + " d: "+d );
}
}
}
}
System.out.println("\n\n");
}
public static void main(String[] args) {
bruteForce();// O(n^4)
littleBetter(); // O(n^3)
System.out.println( Math.pow(0,1/3));
System.out.println( Math.pow(0,1));
System.out.println( Math.pow(0,0));
System.out.println( Math.pow(34,0));
System.out.println( Math.pow(34,-0));
System.out.println( Math.pow(0,1));
}
}
If you execute the program, you will see that the no of row of result are different too.
Output
🛑 ~/Documents/CTCI Codes >> javac Find_a3_b3__c3_d3.java
🛑 ~/Documents/CTCI Codes >> java Find_a3_b3__c3_d3
0 a: 0 b: 0 --- c: 0 d: 0
1 a: 0 b: 1 --- c: 0 d: 1
2 a: 0 b: 1 --- c: 1 d: 0
3 a: 0 b: 2 --- c: 0 d: 2
4 a: 0 b: 2 --- c: 2 d: 0
5 a: 0 b: 3 --- c: 0 d: 3
6 a: 0 b: 3 --- c: 3 d: 0
7 a: 0 b: 4 --- c: 0 d: 4
8 a: 0 b: 4 --- c: 4 d: 0
9 a: 1 b: 0 --- c: 0 d: 1
10 a: 1 b: 0 --- c: 1 d: 0
11 a: 1 b: 1 --- c: 1 d: 1
12 a: 1 b: 2 --- c: 1 d: 2
13 a: 1 b: 2 --- c: 2 d: 1
14 a: 1 b: 3 --- c: 1 d: 3
15 a: 1 b: 3 ---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8 64 27 1.0
2 4 4
8 64 64 1.0
3 0 0
27 0 0 1.0
3 0 1
27 0 1 1.0
3 0 2
27 0 8 1.0
3 0 3
27 0 27 1.0
3 0 4
27 0 64 1.0
3 1 0
27 1 0 1.0
3 1 1
27 1 1 1.0
3 1 2
27 1 8 1.0
3 1 3
27 1 27 1.0
7 a: 3 b: 1 --- c: 3 d: 1
3 1 4
27 1 64 1.0
3 2 0
27 8 0 1.0
3 2 1
27 8 1 1.0
3 2 2
27 8 8 1.0
3 2 3
27 8 27 1.0
3 2 4
27 8 64 1.0
3 3 0
27 27 0 1.0
3 3 1
27 27 1 1.0
3 3 2
27 27 8 1.0
3 3 3
27 27 27 1.0
3 3 4
27 27 64 1.0
3 4 0
27 64 0 1.0
3 4 1
27 64 1 1.0
3 4 2
27 64 8 1.0
3 4 3
27 64 27 1.0
3 4 4
27 64 64 1.0
4 0 0
64 0 0 1.0
4 0 1
64 0 1 1.0
4 0 2
64 0 8 1.0
4 0 3
64 0 27 1.0
4 0 4
64 0 64 1.0
4 1 0
64 1 0 1.0
4 1 1
64 1 1 1.0
4 1 2
64 1 8 1.0
4 1 3
64 1 27 1.0
4 1 4
64 1 64 1.0
8 a: 4 b: 1 --- c: 4 d: 1
4 2 0
64 8 0 1.0
4 2 1
64 8 1 1.0
4 2 2
64 8 8 1.0
4 2 3
64 8 27 1.0
4 2 4
64 8 64 1.0
4 3 0
64 27 0 1.0
4 3 1
64 27 1 1.0
4 3 2
64 27 8 1.0
4 3 3
64 27 27 1.0
4 3 4
64 27 64 1.0
4 4 0
64 64 0 1.0
4 4 1
64 64 1 1.0
4 4 2
64 64 8 1.0
4 4 3
64 64 27 1.0
4 4 4
64 64 64 1.0
1.0
0.0
1.0
1.0
1.0
0.0
🛑 ~/Documents/CTCI Codes >>
When you divide two integers the answer becomes an integer too, that's because you get 1 instead of zero. 1/3 is equal to zero and Math.pow(0,0) is equal to 1. instead you can use Math.pow(0,1./3)) to get 0.UPDATE You can check this to see better solution that are already provided.
As I stated in a comment the problem you encounter is probably due to 1/3 being evaluated as 0. Casting 1 or 3 to a floating point number should solve that.
How ever, I would suggest further optimization: calculate x^3 for x = 1 to n and store results in both an array and a hash set. Then for every combination of 3 numbers in the array test if a+b-c is in the hash set (due to symmetry of a+b you can also spare some duplicates by iterating slightly better on b).
Edit: granted, my optimization sacrifices space complexity.
I am working on a lab for a class where a user inputs a number and it recursively prints out a number pattern. For example,
The base case is if they enter 1, it will print: 1
If they enter 2 it will print: 1 2 1
If 3, it will print: 1 2 1 3 1 2 1
and then for something bigger, if they enter 7, it will print:
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 6
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 7
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 6
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
I'm a little stuck on what the number pattern is to be able to complete this problem. Does anyone have any ideas?
So you need to write a recursive function. Something of this form:
private String pattern(int num) {
// ...
}
The most important part is finding the right exit condition that should stop the recursion. In this case, that's when num == 1.
From the description, it looks like for a number k,
the output is pattern(k - 1) + k + pattern(k - 1).
I already spoiled too much.
You might need to improve the efficiency of this.
For example, realize that you don't need to run pattern(k - 1) twice,
it's enough to do it once.
I'm a little stuck on what the number pattern is to be able to
complete this problem.
Lets try to analyse the sequence using some function f
f(1) = 1 (Total digits = 1)
f(2) = 1 2 1 ( Total digits = 3)
f(3) = 121 3 121 (Total digits = 7)
f(4) = 1213121 4 1213121 (Total digits = 15)
f(5) = 121312141213121 5 121312141213121 (Total digits = 31)
So as you can observe total digits sequence looks like 1,3,7,15,31,....2^n-1
Now we can express this logic as mentioned below(Note : in order to help you to better understand how the program works i am printing sequence at every level)
public class SequenceGenerator {
public static void main(String[] args) {
generate(7);
}
static void generate(int depth) {
recursiveGenerator(1, null, depth);
}
static void recursiveGenerator(int num, String prev, int limit) {
if (num <= limit) {
if (prev != null) {
System.out.println();
}
if (prev != null) {
System.out.printf("%s %d %s", prev, num, prev);
} else {
prev = "";
System.out.printf("%d", num);
}
if (prev.equals("")) {
prev += num + prev;
} else {
prev += " " + num + " " + prev;
}
recursiveGenerator(++num, prev, limit);
}
}
}
Outputs
1
1 2 1
1 2 1 3 1 2 1
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 6 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 6 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 7 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 6 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
So I have a simple program that creates a LinkedList array of given size n, with each value in the list representing a new separate LinkedList data Structure.
public class Graph {
public final LinkedList[] graph;
public Graph(int n){
graph = new LinkedList[n];
for (int i=0; i<n; i++){
graph[i] = new LinkedList();
}
}
public void addEdge(int x, int y){
graph[x].addFirst(y);
graph[y].addFirst(x);
}
For some reason, however, when I call the addEdge() method with two int values, instead of adding them to the specific called LinkedList in graph[], it adds them to every LinkedList in graph[].
What is the problem here?
Edit:*
public void addEdge(int x, int y){
graph[x].addFirst(y);
graph[y].addFirst(x);
for (int i=0; i<graph.length; i++){
Node tmp = graph[i].first;
System.out.println(i + ":");
while (tmp != null){
System.out.print(tmp.name + " ");
tmp = tmp.Rnext;
}
System.out.println();
}
System.out.println();
}
public class Test {
public static void main(String[] args) {
Graph myGraph1 = new Graph(8);
myGraph1.addEdge(1, 2);
myGraph1.addEdge(1, 7);
myGraph1.addEdge(1, 4);
myGraph1.addEdge(2, 5);
myGraph1.addEdge(2, 6);
myGraph1.addEdge(6, 3);
myGraph1.addEdge(3, 8);
myGraph1.addEdge(5, 7);
}
}
Here is the output of graph:
0:
1 2
1:
1 2
2:
1 2
3:
1 2
4:
1 2
5:
1 2
6:
1 2
7:
1 2
0:
1 7 1 2
1:
1 7 1 2
2:
1 7 1 2
3:
1 7 1 2
4:
1 7 1 2
5:
1 7 1 2
6:
1 7 1 2
7:
1 7 1 2
0:
1 4 1 7 1 2
1:
1 4 1 7 1 2
2:
1 4 1 7 1 2
3:
1 4 1 7 1 2
4:
1 4 1 7 1 2
5:
1 4 1 7 1 2
6:
1 4 1 7 1 2
7:
1 4 1 7 1 2
0:
2 5 1 4 1 7 1 2
1:
2 5 1 4 1 7 1 2
2:
2 5 1 4 1 7 1 2
3:
2 5 1 4 1 7 1 2
4:
2 5 1 4 1 7 1 2
5:
2 5 1 4 1 7 1 2
6:
2 5 1 4 1 7 1 2
7:
2 5 1 4 1 7 1 2
0:
2 6 2 5 1 4 1 7 1 2
1:
2 6 2 5 1 4 1 7 1 2
2:
2 6 2 5 1 4 1 7 1 2
3:
2 6 2 5 1 4 1 7 1 2
4:
2 6 2 5 1 4 1 7 1 2
5:
2 6 2 5 1 4 1 7 1 2
6:
2 6 2 5 1 4 1 7 1 2
7:
2 6 2 5 1 4 1 7 1 2
0:
6 3 2 6 2 5 1 4 1 7 1 2
1:
6 3 2 6 2 5 1 4 1 7 1 2
2:
6 3 2 6 2 5 1 4 1 7 1 2
3:
6 3 2 6 2 5 1 4 1 7 1 2
4:
6 3 2 6 2 5 1 4 1 7 1 2
5:
6 3 2 6 2 5 1 4 1 7 1 2
6:
6 3 2 6 2 5 1 4 1 7 1 2
7:
6 3 2 6 2 5 1 4 1 7 1 2
Here is the LinkedList and Node Class I am using:
import java.util.NoSuchElementException;
public class LinkedList {
public static Node first;
public LinkedList(){
first = null;
}
// Returns true if the list is empty
public boolean isEmpty(){
return first == null;
}
// Inserts a new node at the beginning of this list.
public void addFirst(int name){
first = new Node(name, first);
}
public boolean findData(int d){
if(first == null) throw new NoSuchElementException();
Node tmp = first;
while (tmp != null) {
if (tmp.name == d) return true;
tmp = tmp.Rnext;
} return false;
}
}
public class Node {
public int name;
public Node Rnext;
public Node(){
name = 0;
Rnext = null;
}
public Node(int n, Node r){
this.name = n;
this.Rnext = r;
}
}
public static Node first;
This is the problem. Every single LinkedList you make is sharing the same Node, so they're all effectively the same list.
Don't use static for instance variables.