Hey guys so I have to find the last 10 elements in my array in my .txt file filled with unsorted primes. The problem I'm having is the code I'm using to get the last 10 elements is just returning the same number instead of the last ten digits. If anyone can help me figure it out that would be great.
Also i have looked through some other code to figure it out, but i had no luck. If you do answer please don't just answer with a link to someone else code. Thanks
Heres my code so far:
public class BubbleSort {
static long BubbleSortCount = 0;
public static void main(String[] args) throws IOException {
System.out.print("This program compares the bubble, selection, merge sorts.\n"
+ "The data set is 78498 unsorted integers (prime numbers less than 1,000,000)\n\n");
File file = new File("primes1.txt");
Scanner infile = new Scanner(file);
ArrayList<Integer> Primes1 = new ArrayList<Integer>();
int temp;
long startTime, endTime;
int n;
while (infile.hasNextInt()) {
n = infile.nextInt();
Primes1.add(n);
}
// bubble
System.out.print("BUBBLE SORT\n");
System.out.println("\nPrimes Read : " + Primes1.size());
startTime = System.currentTimeMillis();
Primes1 = Bubble(Primes1);
endTime = System.currentTimeMillis();
System.out.println("Elapsed Seconds = "
+ (double) ((endTime - startTime) / 1000.0));
System.out.println("iterations = " + BubbleSortCount++);
System.out.print("First 10 sorted : ");
for (int i = 0; i < 10; i++) {
System.out.print(Primes1.get(i) + " ");
}
System.out.println();
System.out.print("Last 10 sorted : ");
for (int i = 0; i < 10; i++) {
System.out.print(Primes1.get(Primes1.size() - 1) + " ");
}
}
// Bubble sort Method
public static ArrayList<Integer> Bubble(ArrayList<Integer> Primes1) {
int temp;
for (int i = 0; i < Primes1.size() - 1; i++) {
for (int j = 0; j < Primes1.size() - 1; j++) {
BubbleSortCount++;
if (Primes1.get(j) > Primes1.get(j + 1)) {
temp = Primes1.get(j);
Primes1.set(j, Primes1.get(j + 1));
Primes1.set(j + 1, temp);
}
}
}
return Primes1;
}
}
Here are the numbers in my .txt file.
7
2
47
13
11
59
17
41
37
23
29
31
19
53
43
241
251
257
263
269
271
277
281
283
293
System.out.print(Primes1.get(Primes1.size() - 1) + " ");
With the 1 it will always take the same number, should be fixed
System.out.print(Primes1.get(Primes1.size() - i) + " ");
Change:
for (int i = 0; i < 10; i++) {
System.out.print(Primes1.get(Primes1.size() - 1) + " ");
}
To:
for (int i = 0; i < 10; i++) {
System.out.print(Primes1.get(Primes1.size() - (i+1)) + " ");
}
Or:
for (int i = 1; i <= 10; i++) {
System.out.print(Primes1.get(Primes1.size() - i) + " ");
}
The reason you get the same number is that you never use the index in the for-loop to get the 10 last.
This:
System.out.print("Last 10 sorted : ");
for (int i = 0; i < 10; i++) {
System.out.print(Primes1.get(Primes1.size() - 1) + " ");
}
must be changed to use the loop index variable. This should do it:
System.out.print("Last 10 sorted : ");
for (int i = 0; i < 10; i++) {
System.out.print(Primes1.get(Primes1.size() - 10 + i) + " ");
}
Another way would be to use the sublist method from the List interface to produce a new list with the 10 last elements, like this:
List<Integer> last10list = Primes1.subList(Primes1.size() - 11, Primes1.size());
Related
import java.util.*;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size ??");
int n = sc.nextInt();
int[] marks = new int[n + 1];
for (int i = 0; i < n; i++) {
System.out.println("Enter " + i + " number ??");
marks[i] = sc.nextInt();
}
System.out.println("The following numbers are : ");
for (int j = 0; j < marks.length - 1; j++) {
System.out.println(marks[j] + " ");
}
int max = marks[0];
int min = marks[0];
int s = marks.length;
for (int i = 0; i < s; i++) {
if (marks[i] > max) {
max = marks[i];
}
if (marks[i] < min) {
min = marks[i];
}
}
System.out.println("Max is " + max + " Min is " + min);
}
Output:
Enter the size ??2
Enter 0 number ??
56
Enter 1 number ??
56
The following numbers are :
56
56
Max is 56 Min is 0
Hello and welcome to StackOverflow. Next time, febore you jump into the internet for help, please try this approach. It will solve your problem much quicker.
for (int i = 0; i < s; i++) {
System.out.println("DEBUG: number in index " + i + " is " + marks[i]);
if (marks[i] > max) {
System.out.println("DEBUG: number is greater than current max " + max);
max = marks[i];
}
if (marks[i] < min) {
System.out.println("DEBUG: number is smaller than current min " + min);
min = marks[i];
}
}
This process is called "debugging". It can be done by adding spurious amount of logging like above or by stepping through the code with a debugger.
The size of mark array is 3 in the above example
int[] marks = new int[n + 1];
Let total number of marks is (n) : 2
We are creating the array with size of 3.
By default value for int primitives in java is 0
marks array is created with size 3
{56, 56, 0}
As per the logic the minimum value among these three elements are 0
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();
}
Program code works correctly, except the output repeats some of the
inputs. I can't seem to figure out why it repeats the first entry as well as the last entry.
import java.util.Scanner;
public class ArraySum {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
final int NUM_ELEMENTS = 8; // Number of elements
int[] userVals = new int[NUM_ELEMENTS]; // User input
int i = 0; // Loop index
int greaterVal = 0; // Find greater #'s than 21
// Prompt user to populate array
System.out.println("Enter " + NUM_ELEMENTS + " integer values...");
for (i = 0; i < NUM_ELEMENTS; ++i) {
System.out.println("Value: ");
userVals[i] = scnr.nextInt();
}
// Determine #'s greater than 21
int greaterVal = userVals[0];
System.out.print("#'s greater than 21 are: ");
for (i = 0; i < NUM_ELEMENTS; ++i) {
if (userVals[i] >= 21) {
greaterVal = userVals[i];
}
// Code is supposed to only display #'s greater than 21 once
System.out.print(" " + greaterVal + " ");
}
return;
}
}
for (i = 0; i < NUM_ELEMENTS; ++i) {
if (userVals[i] >= 21) {
greaterVal = userVals[i];
}
// Code is supposed to only display #'s greater than 21 once
System.out.print(" " + greaterVal + " ");
}
formatting is very bad, and this fragment is not correct. You should print value at once, not save it for later.
This is because you have mention System.out.print(" " + greaterVal + " "); out side of condition if (userVals[i] >= 21), that why if current value in loop less then 21 and if previous value was greater then 21 value which is hold by greaterVal variable then it will print previous value again .
update your code
for (i = 0; i < NUM_ELEMENTS; ++i) {
if (userVals[i] >= 21) {
greaterVal = userVals[i];
// Code is supposed to only display #'s greater than 21 once
System.out.print(" " + greaterVal + " ");
}
}
Also if you just need to print the greater then 21 values, then you don't need greaterVal variable, you just need this
for (i = 0; i < NUM_ELEMENTS; ++i) {
if (userVals[i] >= 21) {
// Code is supposed to only display #'s greater than 21 once
System.out.print( " "+ userVals[i] + " ");
}
}
I need to store the min and max values in an array given, then print them out with specific characters (+ for the maximum values, "-" for the minimum value, and "*" for all the rest).
I think I have most of it completed except for the storing values appropriately so that all the values are not "++++++++++...." like they currently are when printed out.
Any ideas? Help is greatly appreciated.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int numbers[] = new int[24];
int min = Integer.MAX_VALUE;
int max=Integer.MIN_VALUE;
int maxhour = 0;
int minhour = 0;
int total = 0;
char MAX = '+', MIN = '-', MIDDLE = '*';
char currentchar = 0;
for(int i=0; i< numbers.length; i++){
numbers[i] = keyboard.nextInt();
total = total + numbers[i];
if(numbers[i]<min){
min = numbers[i];
minhour = i;
currentchar = MIN;
}else if (numbers[i]>max){
max = numbers[i];
maxhour = i;
currentchar = MAX;
}
}
for(int i=0; i< numbers.length; i++){
System.out.print("Hour " + i + ":");
printTimes(currentchar, numbers[i]);
System.out.println("");
}
System.out.println("Largest Number of hits is : " + max + " at hour " + maxhour);
System.out.println("Average Number of hits is : " + (total/24) + " per hour");
System.out.println("Smallest Number of hits is : " + min + " at hour " + minhour);
}
public static void printTimes(char c, int times) {
if (times >= 70) {
for(int i=0; i< 69; i++){
System.out.print(c);
} System.out.print(">");
} else if (times < 70) {
for(int i=0; i< times; i++)
System.out.print(c);
}
}
}
Example of current output:
42 29 36 7 5 3 10 13 33 40 51 49
22 58 63 102 65 58 48 24 36 48 52 42
Hour 0:++++++++++++++++++++++++++++++++++++++++++
Hour 1:+++++++++++++++++++++++++++++
Hour 2:++++++++++++++++++++++++++++++++++++
Hour 3:+++++++
Hour 4:+++++
Hour 5:+++
Hour 6:++++++++++
Hour 7:+++++++++++++
Hour 8:+++++++++++++++++++++++++++++++++
Hour 9:++++++++++++++++++++++++++++++++++++++++
....
Largest Number of hits is : 102 at hour 15
Average Number of hits is : 39 per hour
Smallest Number of hits is : 3 at hour 5
Just change your last for:
for (int i = 0; i < numbers.length; i++) {
System.out.print("Hour " + i + ":");
if (numbers[i] == min)
currentchar = MIN;
else if (numbers[i] == max)
currentchar = MAX;
else
currentchar = MIDDLE;
printTimes(currentchar, numbers[i]);
System.out.println("");
}
I would update your code as follows -
public static void main(String[] args) {
int numbers[] = new int[24];
int total = 0;
System.out.println("Enter 24 integers please");
Scanner keyboard = null;
try {
keyboard = new Scanner(System.in);
for (int i = 0; i < numbers.length; i++) {
numbers[i] = keyboard.nextInt();
total += numbers[i];
}
} finally {
keyboard.close();
}
Integer min = null;
Integer max = null;
int maxhour = 0;
int minhour = 0;
char MAX = '+', MIN = '-', MIDDLE = '*';
for (int i = 0; i < numbers.length; i++) {
if (min == null || numbers[i] < min) {
min = numbers[i];
minhour = i;
} else if (max == null || numbers[i] > max) {
max = numbers[i];
maxhour = i;
}
}
for (int i = 0; i < numbers.length; i++) {
char currentchar = MIDDLE;
if (i == minhour) {
currentchar = MIN;
} else if (i == maxhour) {
currentchar = MAX;
}
System.out.print("Hour " + i + ":");
printTimes(currentchar, numbers[i]);
System.out.println("");
}
System.out.println("Largest Number of hits is : "
+ max + " at hour " + maxhour);
System.out.println("Average Number of hits is : "
+ (total / 24) + " per hour");
System.out.println("Smallest Number of hits is : "
+ min + " at hour " + minhour);
}
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();
}
}
}