Print numbers in specific range using loops in Java - java

How to print the following sequence using a simple loop in Java
10, 11, 11, 12,12,12,13,13,13,13,14,14,14,14,14

int currentNumber = 10;
int timesToPrint = 1;
int timesPrinted = 0;
while(currentNumber < 15){
System.out.println(currentNumber);
timesPrinted++;
if(timesPrinted == timesToPrint){
timesToPrint++;
timesPrinted = 0;
currentNumber++;
}
}

Well I don't want to do your homework for you, but notice the pattern here. There is 1 10, 2 11s, 3 12s etc....
you need a loop that starts at 10 and ends at 14 which looks like:
for(int i = 10; i<=14; i++){
//print i
}
but instead of just printing i once, you need to print it 1,2,3,4, or 5 times.
One way to do this is to create another variable that starts at 1 and increases every time i increases. Then create another loop nested in the first that prints i that many times. That should be enough to get you started. Feel free to ask questions if you run into trouble.

String s = "";
int timer = 1;
for (int i =10; i<15; i++)
{
for (int a = 0; a<timer; a++)
{
s += i + ", ";
}
timer++;
}
System.out.println(s);

Use this
int num=10;
for(int i=1 ;i<10;i++)
{
for(int j=0;j<i;j++)
{
System.out.print(num+",");
}
num ++;
}

You havent really shown that you have done any work yourself... Anyway
for(int i = 0; i <= 4; i++){
for(int ii = 0; ii <=i; ii++){
int numbertoshow = 10+i;
System.out.print(numbertoshow+", ");
}
}
Output:
10, 11, 11, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 14,
The first loop specifies what the end digit will be (e.g if i = 0, 10+i = 10, so the output will be 10).
The second loop will make it repeat the output (i) times, (e.g, if i = 2, 10+i = 12, so it will output 12 when ii is equal to 0, 1 and 2, hence 3 times)

You need to have a counter in order to know "How many numbers, did you printed so far".
Let me name it counter. You have to Declare it as an integer
By now, we can see that your string of numbers, has a special order, it seems like: counter%10 + 10 (where % sign is represented Modulo calculation).
So by now you can do the following:
public class Printer { // Create a class which its responsibility is to print requested string
public static void main(String[] args) { // The entry point of almost every java program
int end = 4; // As you want to print until 14
for (int counter = 1; counter <= end; ++counter) { // A for loop counts steps so far
for (int i = 0; i < counter; ++i) { // Here we print the number as many as counter
System.out.print(10 + counter%10 + ","); // System.out.print is a bulit in function which prints the given string
}
}
}
}
Now you can change the value of end in third line, in order to get more numbers as well

Related

How do you compare two int arrays elements separately in Java and see which is the greater element?

So I have to make a game that compares two int arrays elements separately and see if one is greater than the other or if they equal and print a message declaring which player won or if it was a draw. Both players are given 7 cards so they have to be compared 7 times each in a different round.
I'm stuck when it comes to comparing each number I cant get seem to get it to work and I don't really know how to make it so every iteration declares a new round would that have to be done separately 7 times?
This is what I currently have after many attempts.
Any help would be greatly appreciated!
public class Exercise1 {
public static void main(String[] args) {
int[] playerOne = new int[6];
int[] playerTwo = new int [6];
playerOne[0] = 10;
playerOne[1] = 6;
playerOne[2] = 8;
playerOne[3] = 9;
playerOne[4] = 7;
playerOne[5] = 12;
playerOne[6] = 7;
playerTwo[0] = 7;
playerTwo[1] = 6;
playerTwo[2] = 9;
playerTwo[3] = 5;
playerTwo[4] = 2;
playerTwo[5] = 8;
playerTwo[6] = 11;
for (int i = 0; i <= playerOne.length - 1; i++) {
if (playerOne[i] < playerTwo) {
}
It looks like you want to compare the elements at the same indices to each other so your code is almost good:
compare playerOne[i] to playerTwo[i] and do whatever is appropriate (e.g. count the score)
keep in mind that the maximum index is defined by the shorter array so either make sure they both have the same length or use i < Math.min(playerOne.length, playerTwo.length).
However, it might be better to rethink your approach (which might be a later exercise though): instead of maintaining 2 separate arrays of "round" scores try to put it into one by introducing a RoundResults class (or similar) and ideally using a list (which has dynamic length).
Example (simplified):
class RoundResult {
private int playerOneScore;
private int playerTwoScore;
//constructor, getters and setters
}
List<RoundResult> rounds = new ArrayList<>();
rounds.add(new RoundResult(10, 7));
rounds.add(new RoundResult(6, 6));
...
for(RoundResult round : rounds) {
if( round.getPlayerOneScore() < round.getPlayerTwoScore() ) {
//player 2 won that round
} else if( round.getPlayerOneScore() > round.getPlayerTwoScore() ) {
//player 1 won that round
} else {
//it was a draw
}
}
Doing it like this has several advantages:
using a list doesn't require to know the number of rounds at compile time (e.g. when you'd want to go on until one player has won at least 2 rounds more than the other with a minimum of x)
you have only one list so you don't have to make sure 2 arrays or lists have the same size and order
you could even add methods to RoundResult like boolean isDraw() { ... }
You need 2 variables that holds each ones score, increment the one that has the bigger card for each round, at the end find the biggest score
int[] playerOne = {10, 6, 8, 9, 7, 12, 7};
int[] playerTwo = {7, 6, 9, 5, 2, 8, 12};
int scorePlayerOne = 0, scorePlayerTwo = 0;
for (int i = 0; i <= playerOne.length - 1; i++) {
if (playerOne[i] < playerTwo[i]) {
scorePlayerTwo++;
} else if (playerTwo[i] < playerOne[i]) {
scorePlayerOne++;
}
}
if (scorePlayerOne < scorePlayerTwo) {
System.out.println("Player Two wins");
} else if (scorePlayerTwo < scorePlayerOne) {
System.out.println("Player One wins");
} else {
System.out.println("Draw");
}
int[] playerOne = {10, 6, 8, 9, 7, 12, 7};
int[] playerTwo = {7, 6, 9, 5, 2, 8, 12};
int position = 0;
for(int i = 0; i< playerOne.length; i++)
position += Integer.compare(playerOne[i], playerTwo[i]);
String result = (position < 0)? "Player One": (position > 0)? "Player Two" : "Equal";
System.out.println(result);
The For loop iterates through one element per array per iteration, and it increments or decrements the 'position' variable by comparing the elements in an iteration.
If Player One is greater then the final value of 'position' would be negative as there were more decrements and vice versa.

How to get code to double values (x * 2) less than 10 in an array? (Java)

I'm taking an online Java programming class (I'm a beginner) and I cannot figure how to correctly complete the code. I've already written what I think is to be included, however I'm missing something that would make the code work completely.
Directions:
Double any element's value that is less than minVal. Ex: If minVal = 10, then dataPoints = {2, 12, 9, 20} becomes {4, 12, 18, 20}.
public class StudentScores {
public static void main (String [] args) {
final int NUM_POINTS = 4;
int[] dataPoints = new int[NUM_POINTS];
int minVal = 0;
int i = 0;
dataPoints[0] = 2;
dataPoints[1] = 12;
dataPoints[2] = 9;
dataPoints[3] = 20;
minVal = 10;
// DO NOT EDIT ANYTHING ABOVE THIS COMMENT. ABOVE IS THE DEFAULT CODE OF ASSIGNMENT
for (i = 0; dataPoints[i] < minVal; ++i) {
dataPoints[i] = dataPoints[i] * 2;
}
// DO NOT EDIT ANYTHING BELOW THIS COMMENT. BELOW IS DEFAULT CODE OF ASSIGNMENT
for (i = 0; i < NUM_POINTS; ++i) {
System.out.print(dataPoints[i] + " ");
}
System.out.println();
return;
}
}
I made comments of what isn't to be messed with, as I am using an online interactive book and cannot edit or change the default code. Additionally, we are working with arrays in this chapter.
I'm new to this site in the sense that I don't know the unwritten ways of stackoverflow, but I've search multiple times online to see how to double the values for an array in java but I do not get the search results I need to help me.
The error messages I get are:
Testing minVal = 10 and dataPoints = {2, 12, 9, 20}
Expected output: 4 12 18 20
Your output: 4 12 9 20
I thought that the compiler should be able to read the lines fully to register that 9 is also less than 10 and thus should be doubled to 18, but it doesn't. What am I missing to make 9 be read as well?
In your code, 12 < 10 evaluates to be false and so, it goes out of loop and hence, it gives Wrong Output. Check the below code:
for (i = 0; dataPoints[i] < NUM_POINTS ; ++i) {
if(dataPoints[i] < minVal) {
dataPoints[i] = dataPoints[i] * 2;
}
}
I looped through all elements of array and if an element is < minVal, I multiplied it by 2.
The second section of the for statement is the termination condition: once it evaluates to false, your loop will stop executing.
In this particular problem, you're trying to look at each value in your dataPoints array, and double it. This calls for the use of an index variable.
Your index variable will keep track of your position within the array as you move from left to right. Starting on the left, at index 0, you will move right until you're at the end of the array.
++i takes care of incrementing your index variable each time the loop runs. This is what moves you through the array.
Your termination condition should check whether you have looked at all values in the array. Once you've gone past all the values in your array your index variable is pointing all the way at the end. And remember, as soon as the termination condition is false your loop will stop executing. So you want to run your code while i (your index variable) is less than the size of the array (dataPoints.length).
Once you've figured out the for loop bounds, simply check your conditional with an if-then statement before updating the values:
for (i = 0; i < dataPoints.length; ++i) {
if (dataPoints[i] < minVal) {
dataPoints[i] = dataPoints[i] * 2;
}
}
for (i = 0; i < NUM_POINTS; ++i) {
if (dataPoints[i] < minVal) {
dataPoints[i] = (dataPoints[i] * 2);
}
}

Array is printing more numbers than intended?

I'm supposed to create and initialize a 100-element array, then make the 7th element the number "7", and finally print the array, starting a new line every 20 elements. I've been trying to figure this out for a long time and I can't.
My code right now is:
public class Array {
public static void main(String args[]) {
int [] array = new int[100];
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
array[a] = a + 1;
}
printArray(array);
}
}
public static void printArray(int[] array){
for (int a=0; a < array.length; a++) {
System.out.print(" " + array[a]);
if ((a - 1) % 20 == 0) {
System.out.println("");
}
}
}
}
When I run this my output is a lot of zeros, far more than 100. They are separated every 20 characters as intended, but the seventh element is not 7. I think it has to do with the association between int "a" and my array, but I can't figure it out. I know the solution must be simple but I just cannot see it. Thank you all!
Proper indentation of your code, in particular the main method, reveals what is going on. You are calling printArray from within the for loop, so you are printing the array contents 100 times.
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
array[a] = a + 1;
}
printArray(array);
}
Move the call to printArray after the } ending brace for the for loop.
Now you'll get 100 0s.
Also, I think you meant to have array[a] = a + 1; executed if the index was not 6, e.g.
if (array[a] == 6) {
array[a] = 7;
} else {
array[a] = a + 1;
}
Additionally, you will want to print a newline after 20 numbers, e.g. after indexes 19, 39, etc., so add 1 to a before calculating the remainder, instead of subtracting 1, so that 19 + 1 = 20, whose remainder is 0.
There are many things wrong. However, to answer your question, you are printing the array 100 times since printArray is inside your first loop.
You misplaced an end parenthesis in your main method. The properly formatted method looks like this:
public static void main(String args[]) {
int [] array = new int[100];
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
}
array[a] = a + 1;
}
printArray(array);
}
First of all your code is organized very badly so it's very easy for u to miss what went where. You have 2 major mistakes, first of all you called printArray()
Inside your for loop and therefore printed it 100 times.
Second, you kept checking if the value inside the array in index a is 6.
You need to check if a is 6 since it is your index like this:
if(a == 6)
array[a] = 7;
Well, I ran your code, and there are a few places that can be corrected.
As for your problem of the many things being printed, that's because you've placed your printarray() inside the for loop, so it's printing the array 100 times.
As for printing it out, i find this code to be more concise:
public static void printArray(int[] array){
int counter = 0;
for(int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
counter++;
if(counter == 20){
counter = 0;
System.out.print("\n");
}
}
}
Also, I'm not really sure why you're using a for loop to just change the 7th element. You could use this:
array[6] = 7;
I'm not really sure what you're doing in the for loop.
I hope this helped! Good luck!

Dealing with overlapping numbers in an array

My program takes a pair of numbers and subtracts them from one another then adds all the differences from the pairs back up for a total.
My problem is that some of the numbers overlap, by numbers I am using start and end times. I need to find a way to disregard overlapping numbers so that an input of
{{10, 14}, {4, 18}, {19, 20}, {19, 20}, {13, 20}
returns a total of 16 and not 27. Thus far I have created another array called hours to check off times already existing. Here is that portion of code:
public static int monitoring(int[][] intervals) {
int sum = 0;
int start = 0;
int end = 0;
boolean[] hours = new boolean[24];
int count = 0;
for(int i = 0; i < intervals.length; i++) {
end = intervals[i][1];
start = intervals[i][0];
for(int j = start; j < end; j++) {
hours[j] = true;
count++;
sum += end - start;
}
}
return sum;
I do not know what you are reaaly trying to get, 2 options possible:
you are probably trying to get difference between maximum of the
2nd element if pairs, and minimum of the 1st element in pairs
you want to count numbers of unique "points" (or hours) in given
interval list.
Simplest solution can be:
if (!hours[j]) {
hours[j] = true;
count++;
}
In this case you do not even need "sum" variable.

finding longest sequence of consecutive numbers

Problem H (Longest Natural Successors):
Two consecutive integers are natural successors if the second is the successor of the first in the sequence of natural numbers (1 and 2 are natural successors). Write a program that reads a number N followed by N integers, and then prints the length of the longest sequence of consecutive natural successors.
Example:
Input 7 2 3 5 6 7 9 10 Output 3 this is my code so far and i have no idea why it does not work
import java.util.Scanner;
public class Conse {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int[] array = new int[x];
for (int i = 0; i < array.length; i++) {
array[i] = scan.nextInt();
}
System.out.println(array(array));
}
public static int array(int[] array) {
int count = 0, temp = 0;
for (int i = 0; i < array.length; i++) {
count = 0;
for (int j = i, k = i + 1; j < array.length - 1; j++, k++) {
if (Math.abs(array[j] - array[k]) == 1) {
count++;
} else {
if (temp <= count) {
temp = count;
}
break;
}
}
}
return temp + 1;
}
}
Why two loops? What about
public static int array(final int[] array) {
int lastNo = -100;
int maxConsecutiveNumbers = 0;
int currentConsecutiveNumbers = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == lastNo + 1) {
currentConsecutiveNumbers++;
maxConsecutiveNumbers = Math.max(maxConsecutiveNumbers,
currentConsecutiveNumbers);
} else {
currentConsecutiveNumbers = 1;
}
lastNo = array[i];
}
return Math.max(maxConsecutiveNumbers, currentConsecutiveNumbers);
}
This seems to work:
public static int longestConsecutive(int[] array) {
int longest = 0;
// For each possible start
for (int i = 0; i < array.length; i++) {
// Count consecutive.
for (int j = i + 1; j < array.length; j++) {
// This one consecutive to last?
if (Math.abs(array[j] - array[j - 1]) == 1) {
// Is it longer?
if (j - i > longest) {
// Yup! Remember it.
longest = j - i;
}
} else {
// Start again.
break;
}
}
}
return longest + 1;
}
public void test() {
int[] a = new int[]{7, 2, 3, 5, 6, 7, 9, 10};
System.out.println("Longest: " + Arrays.toString(a) + "=" + longestConsecutive(a));
}
prints
Longest: [7, 2, 3, 5, 6, 7, 9, 10]=3
Since your question has "Problem H" associated with it, I'm assuming you are just learning. Simpler is always better, so it usually pays to break it down into "what has to be done" before starting on a particular road by writing code that approaches the problem with "how can this be done."
In this case, you may be over-complicating things with arrays. A number is a natural successor if it is one greater than the previous number. If this is true, increment the count of the current sequence. If not, we're starting a new sequence. If the current sequence length is greater than the maximum sequence length we've seen, set the max sequence length to the current sequence length. No arrays needed - you only need to compare two numbers (current and last numbers read).
For example:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int N = scan.nextInt();
int maxSequenceLen = 0; // longest sequence ever
int curSequenceLen = 0; // when starting new sequence, reset to 1 (count the reset #)
int last = 0;
for(int i = 0; i < N; i++) {
int cur = scan.nextInt();
if ((last+1) == cur){
++curSequenceLen;
}
else{
curSequenceLen = 1;
}
if (curSequenceLen > maxSequenceLen){
maxSequenceLen = curSequenceLen;
}
last = cur;
}
System.out.println(maxSequenceLen);
Caveat: I'm answering this on a computer that does not have my Java development environment on it, so the code is untested.
I'm not sure I understand this question correctly. The answer's written here assumes that the the natural successors occur contiguously. But if this is not the same then the solution here might not give the correct answer.
Suppose instead of [7 2 3 5 6 7 9 10] the input was [7 2 6 3 7 5 6 9 10] then the answer becomes 2 while the natural successor [5 6 7] is present in the array.
If the input is not sorted we'll have to use a different approach. Like using HashSet
Load the entire array into a HashSet which removes duplicates.
Pick the first value from the HashSet and assigned it to start and end and remove it from the set.
Now decrements start and check if it is present in the HashSet and continue till a particular value for start is not present int the HashSetwhile removing the value being searched from the set.
Do the same for end except that you will have to increase the value of end for each iteration.
We now have to continuous range from start to end present in the set and whose range is current_Max = end - start + 1
In each iteration we keep track of this current_Max to arrive at the longest natural successor for the entire array.
And since HashSet supports Add, Remove, Update in O(1) time. This algorithm will run in O(n) time, where n is the length of the input array.
The code for this approach in C# can be found here

Categories