I have recently got into java and I need help with a basic program:
public static void main(String[] args) {
Random gen = new Random();
int roll = gen.nextInt(6) + 1;
int[] array = new int[20];
// Replacing all the numbers of the array to random ones
for (int i=0; i<20; i++){
roll = gen.nextInt(6) + 1;
array[i] = roll;
}
// Bracketing all repeating numbers
for (int i=0; i<19; i++){
if (array[i] == array[i++]){
System.out.print("(");
}
System.out.print(array[i]);
if (array[i] == array[i--]){
System.out.print(")");
}
}
}
}
All this code does is take the random die roll and bracket all the numbers that are the same:
13(66)5(2222)(66)71
However, all it does with this code is bracket all the numbers instead of the ones that are the same:
(1)(3)(6)(6)(5)(2)(2)(2)(2)(6)(6)(7)(1)
What am I doing wrong?
Your code is only checking numbers immediately prior to and immediately after the indexed number in array[i].
You could create a second loop inside the first to iterate over all of the numbers in the array to check for a match.
If you do so, you'll need to keep track of the matching numbers with some other mechanism. Immediately printing out a parenthesis as you're currently doing will be problematic with an inner loop.
A simple method to consider is another array that keeps track of whether there was a match or not.
If you are recently got into Java try to avoid i++ and ++i within square brackets. You can solve this problem with a boolean variable that indicates if there is already a bracket open.
After generate random numbers, try this:
boolean openBracket=false;
for (int i=0; i<array.length-1; i++){
if (array[i] == array[i+1] && !openBracket){
System.out.print("(");
openBracket=true;
}
System.out.print(array[i]);
if(array[i] != array[i+1] && openBracket){
System.out.print(")");
openBracket=false;
}
}
Related
I'm doing a little google interview question. Find the pair of numbers in a loop that add up to the number given. I found the numbers 2 and 6 that make up 8 so I say match = true so that the while loop stops, however it still proceeds until it finds the second which is 6 and 2 however, those numbers I have already found just the other way around and I had expected my loop to break as my if statement states if there is any 2 numbers that give the sum, match = true therefore terminating the loop, I guess I am wrong though.
However, if I get rid of the while statement and just return; once a match is found it breaks without looking for the second match (which I want it to).
Why is this happening, the logic of both seems the exact same to me.
Using the while(condition) Method
public class Main {
public static void main(String[]args){
int[] list = new int[]{1,2,1,1,1,6};
boolean match = false;
int sumNeeded = 8;
while(!match){
for(int i = 0; i < list.length; i ++){
for(int j = (list.length -1); j >= 0; j --){
if(list[i] != list[j]){
if(list[i] + list[j] == sumNeeded){
System.out.println("The numbers are = " + list[i] + " & " + list[j]);
match = true;
}
}
}
}
}
}
}
Using return
public class Main {
public static void main(String[]args){
int[] list = new int[]{1,2,1,1,1,6};
int sumNeeded = 8;
for(int i = 0; i < list.length; i ++){
for(int j = (list.length -1); j >= 0; j --){
if(list[i] != list[j]){
if(list[i] + list[j] == sumNeeded){
System.out.println("The numbers are = " + list[i] + " & " + list[j]);
return;
}
}
}
}
}
}
In your while-loop implementation, if the array doesn't have the desired pair at all it would result in an infinite loop. There is no need for the while statement in your solution.
After you enter into the while loop, you look for all the possible pairs in the array and then check for their sum. If it equals the desired sum, you make the boolean variable match as true.
But, until the nested for loop is completely executed (i.e., all the possible pairs are checked) we do not check for the while condition. The entire nested for loop is executed in one iteration of the while loop. Then, the while loop condition is checked again.
As by the end of the first iteration of the while loop all the possible pairs are accounted for, there is no need for a while loop.
Moreover, there are other logical errors in your implementation. The correct brute-force implementation is as follows:
public class Main {
public static void main(String[]args){
int[] list = new int[]{1,2,1,1,1,6};
boolean match = false;
int sumNeeded = 8;
for(int i = 0; i < list.length; i ++){
for(int j = (list.length -1); j > i; j --){
if(list[i] + list[j] == sumNeeded){
System.out.println("The numbers are = " + list[i] + " & " + list[j]);
return;
}
}
}
}
}
The inner-for loop is modified to reduce the double-counting of the unordered pairs. Whenever a match is found and printed, we exit the function.
You may also add a break statement inside the while loop in your initial implementation.
if(match == true) {
break;
}
The while condition continues to execute the first and second for-loop until it's finished where as with return it stops execution entirely from the first and second loop.
To fix the while loop you could use a label and then break from that.
firstLoop:
for(int i = 0; i < list.length; i ++) {
match = true;
break firstLoop;
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!
import java.util.Scanner;
public class Taxi {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int groups = input.nextInt();
int counter=0;
int[] pass = new int[groups];
for(int i=0; i<groups; i++){
pass[i] = input.nextInt();
}
for(int i=0; i<groups; i++){
if(pass[i]==4)
counter++;
else if(pass[i]+pass[i+1]<=4){
counter++;
i++;
}
else
counter++;
}
System.out.println(counter);
}
}
keep on receiving error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Taxi.main(Taxi.java:21)
please help
This line appears to be causing the exception:
else if(pass[i]+pass[i+1]<=4){
You're limiting i to be less than groups, which is the size of the array, but then you deliberately run off the end by using i+1.
Check if i is less than one less than groups first.
else if ( (i < groups - 1) && (pass[i]+pass[i+1]<=4)){
else if(pass[i]+pass[i+1]<=4) line is your killer definitely.
the reason is you are using for loop with i < groups
for(int i=0; i<groups; i++)
so i+1 goes to equals to groups for the last iteration.
say for example , it the groups size is 5 then for loop becomes
for(int i=0;i<5;i++)
we can have group[0] ... groups[4] max
and groups[5] causes array index out of bound exception.
if we check for loop like above then when i goes to 4 then it satisfies for loop check as 4<5 and enters for loop but there you are doing pass[i] -> ok but pass[i+1] will become like pass[5] which definitely causes array index out of bound exception
so check for loop like below
for(int i=0; i<groups-1; i++)
it will work now even for the last element.
I am trying to come up with a program that will search inside of an array that is given a length by the user that picks out whether there is a pair of numbers that sum to 7. The idea is that if there is k amount of dice being thrown, how many pairs of numbers out of those dice thrown add up to 7. So far this is all that I could come up with but I am very stuck.
This is the driver class for the program. I have to write a class that will make this driver function properly.
import java.util.Scanner;
public class SevenDriver{
public static void main(String[] args){
System.out.println("Enter number of dice to toss");
Scanner s = new Scanner(System.in);
int diceCount = s.nextInt();
SevenTally t = new SevenTally(diceCount);
int experiments = 1000000;
int wins = 0;
for(int j = 0; j < experiments; j++)
if(t.experiment()) wins++;
System.out.println((double)wins/experiments);
}
}
This is what I have so far. It does not currently work or compile. I am just looking for some ideas to get me going. Thanks!
public class SevenTally{
private int diceCount;
public SevenTally(int die){
diceCount = die;
}
public int genDice(){
return 1 + (int)(Math.random()*6);
}
public boolean experiment(){
boolean[] nums = new boolean[diceCount];
int ranNum;
int sum = 7;
for(int i = 0; i < nums.length; i++){
ranNum = genDice();
if (nums[ranNum] == sum){
return true;
}
}
int left = 0;
int right = nums.length - 1;
while(left<right){
int tempSum = nums[left] + nums[right];
if(tempSum == 7){
return true;
}
else if(tempSum>7){
right--;
}
return false;
}
}
First populate your array of length k with random int in [1;6]
The number of possible pairs in an array of length k is the number of 2-combinations in the array, which is (k-1)*k/2 (http://en.wikipedia.org/wiki/Combination)
You can test all the possible pairs (i,j) in your array like so:
int win = 0;
int tally = 7;
for(int i=0; i<k-1; i++){
for(int j=i+1; j<k; j++){
if(array[i]+array[j] == tally){
win++;
}
}
}
What this does is that it sets the first element of the pair to be the first element of the array, and sums it with the other elements one after the other.
It pairs array[0] with array[1] to array[k-1] at the first pass of the i for loop, that's k pairs.
Then k-1 pairs at second pass, and so on.
You end up with (k)+(k-1)+(k-2)+...+1 pairs, and that's exactly (k-1)*k/2 pairs.
done =]
edit: sorry, haven't read the whole thing. the method experiment() is supposed to return a boolean. you can return win>0?true:false; for example...
This Wiki page has some algorithms to do that. Its not a trivial problem...
You're generating a random number in ranNum, and then using it as an index into the array nums. Meanwhile, nums never gets filled, so no matter which box you index into, it never contains a 7.
What you want to do, if I understand your problem correctly, is fill each space in the array with the result of a die roll, then compare every two positions (rolls) to see if they sum to seven. You can do that using a nested for loop.
Essentially, you want to do this: (written in pseudocode as I'm not a java programmer)
int[] results[numrolls]
for (count = 0 to numrolls-1) { results[numrolls]=dieRoller() }
for (outer = 0 to numrolls-2)
for (inner = outer+1 to numrolls-1)
if (results[outer] + results[inner] == 7) return true
return false;
However, in this case there's an even easier way. You know that the only ways to get a sum of 7 on 2d6 are (1,6),(2,5),(3,4),(4,3),(5,2),(6,1). Set up a 6-length boolean array, roll your dice, and after each roll set res[result] to true. Then return (1-based array used for simplicity) ( (res[1] && res[6]) || (res[2] && res[5]) || (res[3] && res[4]) ).
ArrayIndexOutOfBoundsException means you are trying to access an element of the array that hasn't been allocated.
In your code, you create a new array d of length diceCount, but then you genDice() on always 6 elements.
I have a specification as below:
Write a program that prints out all the permutations of two numbers that add up to 7. Hint: you can use two nested for loops.
I have done this but I know this is not correct. What numbers should I put in?
public class NestedFor {
public static void main(String[] args) {
for(int i=1; i<=3; i++) {
for(int j=1; j<=i; j++) {
System.out.println(i+ " " +j);
}
}
}
}
Try this (I am assuming you want non-negative numbers, otherwise you have infinite possibilities):
for(int i=0; i<=7, i++)
{
System.out.println(i + "+" + (7-i));
}
No need for two for loops.
If instead of non-negative you require positive numbers, this would become:
for(int i=1; i<7, i++)
{
System.out.println(i + "+" + (7-i));
}
You are almost there. Here are the things that you need to consider:
Assuming that the numbers are required to be positive, the outer loop should go from 1 to 6, inclusive, not from 1 to 3.
Numbers do not need to be in order. Hence, you should not stop the inner loop at i, also going from 1 to 6, inclusive
You need to add an if check before printing i and j.
Once you fix the three things above, your program should work. Good luck!
Your loops should both loop between 1 and 7. Then inside the last for loop you need to check if the sum of i and j equals 7. If it does, print those two numbers.
You really don't need a nested loop.
for (ii = 0; ii<8; ii++) {
System.out.printf("(%d, %d)\n",ii,7-ii);
}
Keep it simple.
I know the "hint" said you could use two nested loops; but in my experience a little bit of cleverness should not be ignored. When your problem gets much larger, being O(n) rather than O(N^2) is a huge difference...
Try this:
for(int i=0;i<7;i++){ //First Loop
for(int j=7;j>0;j--){//Send loop
if((i+j)==7) System.out.println(i+" , "+j); //Permutations printed to terminal
}
}
I guess it's self explaining, two loops going towards each other. Run it and see the lovely result ;)
In mathematics, the notion of permutation relates to the act of permuting (rearranging) objects or values.
A couple of adjustments: I'm taking the liberty of posting a solution but please make sure you understand it!
for (int i = 0; i <= 7/*Need to consider all numbers from 0 to 7*/ ; ++i) {
for (int j = 0; j <= i /*Don't overoptimise: this is good enough and will not generate duplicates*/; j++) {
if (i + j == 7){
System.out.println(i+ "," +j);
}
}
}
It's not the fastest way; spend some time optimising once you have a solution.
public class NestedFor {
public static void main(String[] args) {
for(int i=1; i<=7; i++) {
for(int j=1; j<i; j++) {
if (i + j == 7 ) {
System.out.println(i+ " " +j);
}
}
}
}
}
Check if they add up to 7
if (i+j == 7)
{
//then they add to 7
}
They should both be between 1 and 7 though if you want all numbers between 1 and 7 that add up to 7. If you want to include 0 then start there.
for (int i=1; i<=7; i++)
...and you may want to exclude duplicates
for(int i=1; i<=7; i++) {
for(int j=i; j<=7; j++) { //starts at i, not 1
/* Only check j against numbers equal to or lower than itself
/* to avoid duplicates
*/
}
}
Additionally
Class names should start with a capitol letter, by convention, and in camel case (each word in a phrase has capitol letters
NestedFor