I'm trying read a set of numbers from a file and then isolate the lines in between the first line (which lets us know how many lines will need to be worked on, in this case, 5) and the seventh line (mind you that this is just an example, the range of the lines will is subject to change) so that I can populate a list in the format of (0 1 98, 0 2 5, ...,4 3 15). Right now my code manages to get (0 1 98, 0 2 5, 0 3 16, 0 4 16) added into the list but not the rest. I'm not sure what I've done wrong. Any help would be much appreciated.
Example input:
5
0 1 98 2 5 3 16 4 16
1 0 13 2 47 3 3 4 40
2 0 71 1 51 3 43 4 30
3 0 20 1 94 4 46
4 0 1 1 10 2 28 3 15
2
2 3
2
0 1
public static void t() {
List<String> L = new ArrayList();
try {
BufferedReader f = new BufferedReader(new FileReader("graph.txt"));
String s = f.readLine();
int nodes = Integer.parseInt(s);
int c = -1;
int c1 = 2;
int c2 = 3;
for (int i = 0; i < nodes; i++) {
s = f.readLine();
String z [] = s.split(" ");
String start = z[0];
for (int j = 0; j < z.length; j++) {
int t = c+c1;
int t2 = c+c2;
if (t >= z.length) {
break;
}
String des = z[t];
if (t2 >= z.length+1) {
break;
}
String weight = z[t2];
L.add(start + " " + des + " " + weight);
c1+=2;
c2+=2;
}
}
for (int i = 0; i < L.size(); i++) {
System.out.println(L.get(i));
}
} catch (Exception ex) {
System.out.println(ex);
}
}
You just need to reset your C variables within the outer loop.
for (int i = 0; i < nodes; i++) {
s = f.readLine();
String z [] = s.split(" ");
String start = z[0];
// Declare the variables here, otherwise code is the same
int c = -1;
int c1 = 2;
int c2 = 3;
for (int j = 0; j < z.length; j++) {
int t = c+c1;
int t2 = c+c2;
if (t >= z.length) {
break;
}
String des = z[t];
if (t2 >= z.length+1) {
break;
}
String weight = z[t2];
L.add(start + " " + des + " " + weight);
c1+=2;
c2+=2;
}
}
Related
How to print the triangle below:
2 3 5 8 3 8
4 6 9 4 9
7 1 5 1
2 6 2
7 3
4
First you need to start with number 2 and add one to the next one vertically
My code:
int d = 2, n = 6;
for (int line=1; line <= n; line++ ) {
for (int j = 2; j <= line; j++) {
System.out.print(" ");
}
for (int k = line; k <= n; k++) {
System.out.print(d + " ");
d = d + k;
if (d > 9) {
d = d - 9;
}
}
System.out.println();
}
Result:
2 3 5 8 3 8
5 7 1 5 1
7 1 5 1
7 2 7
4 9
6
The pattern is that the value of d has to be calculated initially on every new line based on the value of d in the first instance of the previous line. That is the part that's missed here. You can do that by having a temp variable store the initial value of d on every line and print based on that. I have used a variable tempD here, which can help print the pattern that you require.
int d = 2, n = 6;
int tempD = d - 1;
for (int line = 1; line <= n; line++) {
tempD = tempD + line;
if (tempD > 9) {
tempD = tempD - 9;
}
d = tempD;
for (int j = 2; j <= line; j++) {
System.out.print(" ");
}
for (int k = line; k <= n; k++) {
System.out.print(d + " ");
d = d + k;
if (d > 9) {
d = d - 9;
}
}
System.out.println();
}
I want to print a pattern like :
Till now i have been able to achieve only for odd numbers like :
1
3 5 7
-
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
while (num % 2 == 0 || num < 0) {
num = kb.nextInt();
}
int odd = 1;
for (int i = 1; i <= num; i += 2) {
String a = "";
for (int j = 1; j <= i; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
I am a beginner and new learner. please help
I'm not sure what's the expected result since that pattern is not clear, however this might be what you're looking for:
int evenCounter = 1;
int oddCounter = 2;
for (int i = 1; i <= 10; i++) {
boolean even = (i % 2 == 0);
for (int j = 1; j < i; j++) {
System.out.print((even ? evenCounter : oddCounter) + " ");
evenCounter += even ? 2 : 0;
oddCounter += even ? 0 : 2;
}
System.out.println();
}
Result:
1
2 4
3 5 7
6 8 10 12
9 11 13 15 17
14 16 18 20 22 24
19 21 23 25 27 29 31
26 28 30 32 34 36 38 40
33 35 37 39 41 43 45 47 49
If the length of each row matters, then the second for loop should have a different exit condition I suppose
To get the pattern from 3 5 7, this code would do, where MAX_PATTERN_NUM is the first number of the last line of the pattern (in your example's case, MAX_PATTERN_NUM = 15)
for(int i = 3; i <= MAX_PATTERN_NUM ; i+=3)
for(int j = i; j <= (i + 4); j+=2)
System.out.print(j + " ");
System.out.println();
However, I see no logical way of getting the entire pattern using the same nested for loops, so I hope this helps
How about this:
public void printPattern(){
int evenCounter = 2;
int oddCounter = 1; //counters
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
while (num % 2 == 0 || num < 0) {
num = kb.nextInt(); //input
}
for(int i = 1; i <= num ; ++i){
if(i % 2 == 0)
evenCounter = addNumbers(i, evenCounter); //print line with evenCounter
else
oddCounter = addNumbers(i, oddCounter); //print line with oddCounter
}
}
private int addNumbers(int i, int counter){
for(int j = 0; j < i;){
if(getIntLength(counter) + j > i) //if the number to long
System.out.print(cut(counter, getIntLength(counter) + j - i) + " "); //output the cut version
else
System.out.print(counter + " ");
j += getIntLength(counter);
counter += 2;
}
System.out.println();
return counter;
}
private String cut(int i, int length){
return Integer.toString(i).substring(0,length); //get substring of int
}
private int getIntLength(int i){
return Integer.toString(i).length(); //get the length of int value
}
It's not so simple, but I don't see an easier way
My answer is based on the assumption that the last 2 is a cut off 21
int n,i,j,o=1,e=2;
System.out.println("enter n:");
n=sc.nextInt();
for(i=1;i<=n;i++){
for(j=1;j<=i;j++){
if(i%2!=0){
System.out.print(o);
o+=2;
}
if(i%2==0){
System.out.print(e);
e+=2;
}
}
System.out.println();
}
I made a Java program that prints out a pascal triangle, however I can't figure out how to correctly position it.
Program 1
public class Triangle {
public static void main() {
System.out.println("\nTriangle: ");
int row = 11;
long[][] triangle = new long[row][row];
triangle[1][1] = 1;
System.out.print(triangle[1][1] + "\n");
for (int i = 2; i < row; i++) {
for (int n = 1; n < row; n++) {
triangle[i][n] = triangle[i-1][n-1] + triangle[i-1][n];
if (triangle[i][n] > 0) {
System.out.print(triangle[i][n] + " ");
}
}
System.out.println();
}
}
}
Output:
1
1 1
1 2 1
1 3 3 1
Program 2
public class Triangle {
public static void main() {
System.out.println("\nTriangle: ");
int row = 11;
long[][] triangle = new long[row][row];
int x = 1;
while (x < row - 1) {
System.out.print(" ");
x++;
}
triangle[1][1] = 1;
System.out.print(triangle[1][1] + "\n");
for (int i = 2; i < row; i++) {
x = i;
while (x < row - 1) {
System.out.print(" ");
x++;
}
for (int n = 1; n < row; n++) {
triangle[i][n] = triangle[i-1][n-1] + triangle[i-1][n];
if (triangle[i][n] > 0) {
System.out.print(triangle[i][n] + " ");
}
}
System.out.println();
}
}
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1 //(Notice this line is incorrectly positioned)
When the triangle approaches multiple digit numbers, it starts to break down and makes it ugly. Can someone explain how I can display a normal triangle instead of this ugly one?
Dynamic Pascal Triangle generator is here:
import java.io.IOException;
import java.util.Scanner;
public class Main {
static double fact(int n) {
double result = 1;
for (double i = 1; i <= n; i++)
result *= i;
return result;
}
static double combine(int n, int r) {
return ((fact(n)) / (fact(n - r) * fact(r)));
}
static void pascalTriangle(int n) {
int n2 = n;
for (int i = 0; i < n; i++) {
for (int space = 8 * (n2 - 1); space >= 0; space--) {
System.out.printf(" ");
}
for (int j = 0; j <= i; j++) {
System.out.printf("%14.0f", combine(i, j));
System.out.printf(" ");
}
System.out.println();
n2--;
}
}
public static void main(String[] args)
throws IOException, InterruptedException {
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.print("Enter Number of Lines(n): ");
int n = sc.nextInt();
pascalTriangle(n);
System.out.println("Press any key to exit! ");
sc.nextByte();
}
}
Try this ...
Results:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
import java.util.*;
public class HelloWorld {
static int binCoeff(int n, int k) {
int res = 1;
if (k > n - k)
k = n - k;
for (int i = 0; i < k; ++i) {
res *= (n - i);
res /= (i + 1);
}
return res;
}
static void pascalTriangle(int lines) {
for (int i = 0; i < lines; i++) {
for (int j = 0; j <= i; j++)
System.out.print(HelloWorld.binCoeff(i, j) + " ");
System.out.println();
}
}
public static void main(String[] args) {
System.out.println("Results: ");
HelloWorld.pascalTriangle(8);
}
}
/**
* #author Ranjith
*/
public class JavaApplication2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int i;
int x;
int n = 15; //number of rows
String newLine = System.getProperty("line.separator");
for (i = 0; i < n; i++) { //loop to adjust spacing
x = i;
while (x < n - 1) {
System.out.print(" ");
x++;
}
fib(i); //fibonacci function is called
System.out.print(newLine);
}
}
public static void fib(int num) { //fibonacci function
int[] febo = new int[100];
febo[0] = 0;
febo[1] = 1;
for (int i = 2; i < num; i++) {
febo[i] = febo[i - 1] + febo[i - 2];
}
for (int i = 0; i < num; i++) {
System.out.print(febo[i] + " ");
}
}
}
Output:
0
0 1
0 1 1
0 1 1 2
0 1 1 2 3
0 1 1 2 3 5
0 1 1 2 3 5 8
0 1 1 2 3 5 8 13
0 1 1 2 3 5 8 13 21
0 1 1 2 3 5 8 13 21 34
0 1 1 2 3 5 8 13 21 34 55
0 1 1 2 3 5 8 13 21 34 55 89
0 1 1 2 3 5 8 13 21 34 55 89 144
0 1 1 2 3 5 8 13 21 34 55 89 144 233
You can represent such a triangle as a 2d array, where the elements of the first row and column are equal to one, and all other elements are the sum of the previous element in the row and column.
arr[i][j] = arr[i][j-1] + arr[i-1][j];
Then you can position it in the upper left corner as follows:
1 1 1 1 1 1 1 1 1
1 2 3 4 5 6 7 8
1 3 6 10 15 21 28
1 4 10 20 35 56
1 5 15 35 70
1 6 21 56
1 7 28
1 8
1
Try it online!
public static void main(String[] args) {
int n = 9;
// an array of 'n' rows
int[][] arr = new int[n][];
// iterate over the rows of the array
for (int i = 0; i < n; i++) {
// a row of 'n-i' elements
arr[i] = new int[n - i];
// iterate over the elements of the row
for (int j = 0; j < n - i; j++) {
if (i == 0 || j == 0) {
// elements of the first row
// and column are equal to one
arr[i][j] = 1;
} else {
// all other elements are the sum of the
// previous element in the row and column
arr[i][j] = arr[i][j - 1] + arr[i - 1][j];
}
}
}
// formatted output
for (int[] row : arr) {
for (int el : row) {
// formatting as a number with a trailing space
System.out.printf("%2d ", el); // two-digit number
// System.out.printf("%3d ", el); // three-digit number
// System.out.printf("%4d ", el); // four-digit number
}
System.out.println();
}
}
See also:
• Pascal's triangle 2d array - formatting printed output
• Print Pascal's Triangle
class pascal {
static void main(int n) {
int a[][] = new int[n][n + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = 0;
}
}
a[0][1] = 1;
int k = 5;
int p = 0;
for (int i = 1; i < n; i++) {
for (int j = 1; j < n + 1; j++) {
a[i][j] = a[i - 1][j] + a[i - 1][j - 1];
}
}
for (int i = 0; i < a.length; i++) {
for (p = n + -i; p > 0; p--) {
System.out.print(" ");
}
for (int j = 0; j < a[i].length; j++) {
if (a[i][j] != 0) {
System.out.print(a[i][j] + " ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
How to loop this?
I'm trying to loop this:
0-> 1,2,3
1-> 4,5,6
2-> 7,8,9
3-> 10,11,12
4->.....
......
I don't know how to write this algorithm.
I tried below, it doesn't work.
public class gYie {
public static void main(String[] args) {
int current = 0;
int death = 0;
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
for (int j = 0; j < 3; j++) {
System.out.print(death+j +" ");
current += j;
}
death += current;
System.out.println("");
}
}
}
Its Output is:
run:
0 0 1 2
1 3 4 5
2 9 10 11
3 18 19 20
4 30 31 32
5 45 46 47
6 63 64 65
7 84 85 86
8 108 109 110
9 135 136 137
How to solve this? I can't think how to write it.
3 becomes 18,19,20 instead of 12,13,14.
Looks suspiciously like homework, so here's some pseudo-code (actually Python) that will do the trick for you:
for outer in range (10):
print "%d ->"%(outer),
for inner in range (3):
print "%2d"%(outer * 3 + inner + 1),
print
The basic idea is to simply have an inner loop of 0 through 2 inclusive and an outer loop that increases by one each time. Then the formula:
outer * 3 + inner + 1
gives you the values you want:
0 -> 1 2 3
1 -> 4 5 6
2 -> 7 8 9
3 -> 10 11 12
4 -> 13 14 15
5 -> 16 17 18
6 -> 19 20 21
7 -> 22 23 24
8 -> 25 26 27
9 -> 28 29 30
You're overthinking it. For the left-hand side, all you need to print is i. For the right-hand side , you just need a single variable current that gets incremented every time its printed:
int current = 1;
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
for (int j = 0; j < 3; j++) {
System.out.print(current + " ");
current ++;
}
System.out.println();
}
}
Try this
int loopCount = 1;
for(int a = 1; a < 21; a++){
System.out.println(a);
for(int b = 0; b < 3; b++){
System.out.print((loopCount++) + " ");
}
System.out.println();
}
Edit: But I guess I found a more efficient way by using a single loop
int x = 1;
for(int a = 0; a < 21; a++){
System.out.println(a + " -> " + (x) + " " + (x + 1) + " " + (x + 2));
x = x + 3;
}
now you can merge it with your variables and logic
Here is a solution with a single loop:
int n = 15;
for (int i = 0; i < n; i++) {
if (i % 3 == 0) {
System.out.println();
}
System.out.print(i + " ");
}
You need to do something like this. Just keep printing the current.
int current = 1;
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
for (int j = 0; j < 3; j++) {
System.out.print(current +" ");
current ++;
}
System.out.println();
}
this should do the job...
public class gYie {
public static void main(String[] args) {
for (int i = 0, j = 1; i < 10; i++) {
System.out.print(i + " ");
for (int h = 0; h < 3; h++, j++) {
System.out.print(j +" ");
}
System.out.println("");
}
}
}
You can just simplify your code as follows :
public static void main(String[] args) {
int death = 3;
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
death = 3*i;
for (int j = 1; j <= 3; j++) {
System.out.print(death+j +" ");
}
System.out.println("");
}
}
}
You will now get the output as :-
0 1 2 3
1 4 5 6
2 7 8 9
3 10 11 12
4 13 14 15
5 16 17 18
6 19 20 21
7 22 23 24
8 25 26 27
9 28 29 30
Use a simple counter:
int j = 0;
for (int i = 0; i < 10; i++)
System.out.println(i + " " + ++j + " " + ++j + " " + ++j + " ");
There is a lot of nested loops above. Here's a scalable solution within a single for loop.
public static void main(String[] args) {
int numbersPerLine = 3;
int finalNumber = 12;
int startingRowNumber = 0;
System.out.print(startingRowNumber + " -> ");
for(int i = 0; i < finalNumber; i++) {
if(i > 0 && (i % numbersPerLine) == 0) {
System.out.print("\n" + ((i / numbersPerLine) + startingRowNumber) + " -> ");
} else if(i > 0) {
System.out.print(",");
}
System.out.print((i + 1));
}
}
Change your code like this.
int death = 1;
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
for (int j = 0; j < 3; j++) {
System.out.print(death++ +" ");
//current += j;
}
//death += current;
System.out.println("");
}
Got exact solution for it ...
class Alok{
public static void main(String[] args){
int i = 0,j=0;
for(i=0;i<10;i++){
System.out.print(""+i+"->");
for(j=(i*3)+1;j<(i*3)+4;j++){
System.out.print(""+j+" ");
}System.out.println();
}
}
}
Heres my code that displays i get no errors at all and it works but i have a little output issue with my thing
// Lab13TEXT03st.java
// This is the student starting version of the Lab13 assignment.
// Testing <main> methods are provided for the 80-point and 100-point versions.
// This means that this version will not compile as provided.
import java.util.ArrayList;
public class Lab13TEXT03st
{
public static void main(String[] args)
{
System.out.println("\nLAB26A 80-POINT VERSION\n");
Matrix m2 = new Matrix(3, 5, 100);
//m2.displayMatrix("Matrix m2 3 X 5 Display");
System.out.println();
int count = 100;
System.out.println("Matrix m1 Default Display"); //
System.out.println("Matrix has no elements"); //
System.out.println("");
int pos = 0;
for (int r = 0; r < m2.getRows(); r++)
{
//System.out.println("r = " + r); //
for (int c = 0; c < m2.getCols(); c++)
{
m2.setValue(r,c,count, pos);
pos++;
count++;
//System.out.println("r = " + r + " c = " + c + " and count = " + count); //
}
//System.out.println(""); //
}
m2.displayMatrix("Matrix m2 3 x 5 Consecutive Integers Display");
System.out.println();
Matrix m3 = new Matrix(3,3,100);
m3.displayMatrix("Matrix m3 3 X 3 Initialized to 100 Display");
System.out.println();
}
}
class Matrix {
private ArrayList list; // one-dimensional array stores matrix values
private int listSize; // total number of elements in the matrix
private int numRows; // number of rows in the matrix
private int numCols; // number of cols in the matrix
public Matrix(int r, int c, int value){
list = new ArrayList();
numRows = r;
numCols = c;
listSize = r * c;
//for(int i = 0; i < listSize; i++)
// list.add(new Integer(value));
}
public int getRows(){
return numRows;
}
public int getCols(){
return numCols;
}
public int getSize()
{
return listSize;
}
public int getValue(int r, int c)
{
int rowLength = getRows();
int colLength = getCols();
//System.out.println("r in get = " + r);
int position = (r * colLength) + c;
//int position = ((r + 1) * rowLength) - rowLength + c; // one to multi-dimensional array index conversion
//System.out.print("Pos get = " + position + "; ");
return ((Integer)list.get(position)).intValue();
}
public void setValue(int r, int c, int value, int pos)
{
int rowLength = getRows();
//int colLength = getCols();
//int position = ((r + 1) * rowLength) - rowLength + c; // one to multi-dimensional array index conversion
//System.out.println("Pos set = " + position + "; ");
list.add(pos,new Integer(value));
}
public void displayMatrix(String str)
{
System.out.println(str);
for(int j = 0; j < getRows(); j++){
for(int i = 0; i < getCols(); i++){
System.out.print(getValue(j, i) + " ");
}
System.out.println("");
}
}
}
My output is wrong and i need some help please
I get no errors... here is my output
LAB26A 80-POINT VERSION
Matrix m1 Default Display
Matrix has no elements
Matrix m2 3 x 5 Consecutive Integers Display
100 101 102 103 104
105 106 107 108 109
110 111 112 113 114
Matrix m3 3 X 3 Initialized to 100 Display
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at Matrix.getValue(Lab13TEXT03st.java:128)
at Matrix.displayMatrix(Lab13TEXT03st.java:147)
at Lab13TEXT03st.main(Lab13TEXT03st.java:49)
Process completed.
It needs to output like this though:
LAB13TEXT03 80-POINT VERSION
Matrix m1 Default Display
Matrix has no elements
Matrix m2 3 X 5 Display
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Matrix m2 3 X 5 Consecutive Integers Display
100 101 102 103 104
105 106 107 108 109
110 111 112 113 114
Matrix m3 3 X 3 Initialized to 100 Display
100 100 100
100 100 100
100 100 100
Please help
The second matrix (m3) fails because you haven't initialized it yet, as you did with m2. You never wrote something along the lines m3.setValue(...) in the code. Alternatively, for initializing the matrix with a default value, you need to uncomment these lines in the constructor of Matrix:
for(int i = 0; i < listSize; i++)
list.add(new Integer(value));