Java Calculate Sequence with Queue - java

I have the following sequence of numbers:
S1 = N, S2 = S1 + 1, S3 = 2*S1 + 1, S4 = S1 + 2, S5 = S2 + 1, S6 = 2*S2 + 1, S7 = S2 + 2 ...
Using the ArrayDeque<E> class, I have to write a program to print its first 50 members for given N.
Examples:
input 2
output 2 3 5 4 4 7 5 6 11 7 5 9 6 ...
This is my code. The problem is that I can't update next S
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Scanner;
public class p04 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numN = scanner.nextInt();
scanner.close();
int counter = 1;
int nexS = numN;
Queue<Integer> fifty = new ArrayDeque<>();
for (int i = 0; i < 50; i++) {
if (i == 0){
fifty.add(numN);
}else {
if (counter == 1){
counter++;
numN = nexS + 1;
fifty.add(numN);
}else if (counter == 2){
counter++;
numN = (nexS * 2) + 1;
fifty.add(numN);
}else {
counter = 1;
numN = nexS +2;
fifty.add(numN);
nexS = nexS + 1;
}
}
}
for (Integer integer : fifty) {
System.out.print(integer + " ");
}
}
}

The way you solve this problem it's easier to solve It with ArrayList. I think that my solution is more queue oriented and that was your task. So this is my take:
import java.util.ArrayDeque;
import java.util.Scanner;
public class SequenceQuestion {
public static void constructSequence(int start, int seqLength) {
ArrayDeque<Integer> queue = new ArrayDeque<>();
queue.add(start);
System.out.print(start);
for (int i = 0; i < seqLength - 1; i++) {
int print = 0;
if (i % 3 == 0 && i != 0) queue.remove();
if (i % 3 == 0) {
print = queue.peek() + 1;
queue.add(print);
} else if (i % 3 == 1) {
print = queue.peek() * 2 + 1;
queue.add(print);
} else if (i % 3 == 2) {
print = queue.peek() + 2;
queue.add(print);
}
System.out.print(", " + print);
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
constructSequence(s.nextInt(), 50);
}
}
You don't need counters because you already have one (i) and if you always check for mod 3 at the beginning and if equals to 0, remove the first element from queue. I see that this is the place you had trouble with.

Related

Java For loop !!! printing out values

Write a program that generates a sequence of 20 random die tosses in an array and
that prints the die values, marking only the longest run, like this:
1 2 5 5 3 1 2 4 3 (2 2 2 2) 3 6 5 5 6 3 1
If there is more than one run of maximum length, mark the first one.
I am working on this question and this code works till count the maxCount.
However, I am stuck in printing out the final result which means I am working on the last for loop to print out what the question requires.
But, the result is not what I wanted to get. How can I figure it out?
import java.util.Random;
public class AA {
public static void main(String[] args) {
int count = 1;
int maxCount = 1;
int runEndsAt = 0;
// create array
int[] num = new int[20];
// create random object
Random numbers = new Random();
for (int i = 0; i < 20; i++) {
num[i] = numbers.nextInt(6) + 1;
// added 1 b/c it starts from 0
}
boolean inRun = false;
for (int i = 0; i < num.length; i++) {
if (inRun) {
if (num[i] != num[i - 1]) {
/*
* System.out.print("|" + count +"|");
* System.out.print(") ");
*/ inRun = false;
}
if (inRun) {
System.out.print("|" + count + "|");
count++;
}
}
if (!inRun) {
if (count > maxCount) {
maxCount = count;
runEndsAt = i;
}
count = 1;
if (i < 19)
// comparing index from i to i+1
if (num[i] == num[i + 1]) {
System.out.print("( ");
inRun = true;
}
}
}
if (inRun) {
/*
* System.out.print("|" + count +"|"); System.out.print(" )");
*/ }
for (int i = 0; i < num.length; i++) {
if (i == runEndsAt - maxCount) {
System.out.println("(");
if (i == runEndsAt) {
System.out.println(")");
}
}
}
}
}
If you are in Java - you may want to use StringBuilder.
Solution:
import java.util.stream.IntStream;
public class LongestRun {
public static void main(String[] args) {
// We are told that die tosses is an Array... so we create one.
int[] tosses = IntStream.range(0, 20)
.map(i -> { return (int) (Math.random() * 6 + 1); } )
.peek(System.out::print)
.toArray();
// Counting and generation of output:
int length = 0, longest = 0, startPos = 0;
StringBuilder sb = new StringBuilder(""+tosses[0]);
for (int i=1; i<tosses.length; i++) {
if (tosses[i-1] == tosses[i]) {
length++;
} else {
length=0;
}
if (longest < length) {
longest = length;
startPos = i-length;
}
sb.append("" + tosses[i]);
}
sb.insert(startPos+longest+1, ")");
sb.insert(startPos, "(");
// Final result:
System.out.println("Result:");
System.out.println(sb.toString());
}
}
Sounds like a fun problem. Here is my solution:
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class SO_40307704 {
private final static int NUM_ROLLS = 100;
private final static Pattern PATTERN = Pattern.compile("(\\d)(\\1)+");
public static void main(String... args) {
final Random r = new Random();
final String rolls = Stream.generate(() -> r.nextInt(6) + 1)
.limit(NUM_ROLLS)
.map(i -> Integer.toString(i))
.collect(Collectors.joining());
Matcher m = PATTERN.matcher(rolls);
int start = 1;
int end = 0;
while (m.find()) {
if (m.end() - m.start() > end - start) {
end = m.end();
start = m.start();
}
}
System.out.println(String.format(
"%s(%s)%s",
rolls.substring(0, start),
rolls.substring(start, end),
rolls.substring(end)));
}
}
Hope it helps

Java/Demorgan's Law/Boolean Algebra/Random Dice/

I need some help getting this code to work.
I need to be able to Write a program that counts how many times three six-sided dice must be rolled until the values showing are all different.
Instructions:
Write a driver that generates 10 output runs.
Here is an example of two output runs.
2 6 5
count = 1
5 3 5
3 5 3
3 3 4
1 3 3
2 5 4
count = 5
Here is my code so far, I don't exactly know where and how to apply DeMorgan's law to this.
import java.util.Random;
public class P4_Icel_Murad_Rolling
{
public static void main(String[] args){
P4_Icel_Murad_Rolling obj = new P4_Icel_Murad_Rolling();
obj.rolling(10);
}
public void rolling(int number){
int counter = 0;
Random num = new Random();
for(int i = 0; i < number; i++){
int A = num.nextInt(6);
System.out.print(A + " ");
int B = num.nextInt(6);
System.out.print(B + " ");
int C = num.nextInt(6);
System.out.print(C + " ");
if((){
counter++;
}
System.out.println();
}
}
}
Try this:
(I don't know hot to apply de Morgan's Laws here.)
public static void main(String[] args){
P4_Icel_Murad_Rolling obj = new P4_Icel_Murad_Rolling();
obj.rolling(10);
}
public void rolling(int number){
int counter = 1;
Random num = new Random();
for(int i = 0; i < number; i++) {
int A = num.nextInt(6) + 1;
System.out.print(A + " ");
int B = num.nextInt(6) + 1;
System.out.print(B + " ");
int C = num.nextInt(6) + 1;
System.out.print(C + "\n");
if(A == B || A == C || B == C) {
counter++;
}
System.out.println("count = " + counter);
}
}

Can 5 numbers equal a target number using addition, subtraction, or multiplication

I'm working on a game, much like the Math Dice problem, albeit a bit different. The user rolls a 20 sided die, then 5 more dice following that. To make things simpler, the user cannot reorder the dice, so if they roll 1 2 3 4 5, they can't do operations like 1 + 3 + 2 + 5 + 4. The question is if, using addition, subtraction, and multiplication, can they reach the target number from the 20 sided die?
Now, I know how to do this, just generate a permutation of all possible addition, subtraction, and multiplication of the 5 numbers, but it's the implementing of the solution that's getting me. I've hit a roadblock after a couple tries, so any help is appreciated.
edit: This is my current implementation, without the multiplication, and it isn't working quite right.
import java.util.ArrayList;
import java.util.Scanner;
public class targetDice {
public static void main(String[] args) {
ArrayList<Integer> rolls = new ArrayList<Integer>(); // Array to hold the rolls
ArrayList<Integer> d20 = new ArrayList<Integer>(); // Array to hold all the d20 rolls
Scanner sc = new Scanner(System.in);
int answer = 0;
String record = "";
while (sc.hasNextInt()) {
d20.add(sc.nextInt()); // Adds the d20 rolls
rolls.add(sc.nextInt()); // Adds the first roll
rolls.add(sc.nextInt()); // Adds the second roll
rolls.add(sc.nextInt()); // Adds the third roll
rolls.add(sc.nextInt()); // Adds the fourth roll
rolls.add(sc.nextInt()); // Adds the fifth roll
} // End while loop
for (int i = 0; i < d20.size(); i++) { // Number of times we need to compute: number of d20 rolls
answer = rolls.get(0);
for (int j = 0; j < rolls.subList(0, 5).size(); j++) { // Go through each roll given
if (d20.get(i) > answer || d20.get(i).equals(answer)) { // If the d20 roll is higher than the first roll or if it's equal
answer += rolls.get(j);// then take the running total and add it
record += " + ";
} else if (d20.get(i) < answer) {
answer -= rolls.get(j);
record += " - ";
}
}
System.out.println(answer);
//TODO: This if else block is our final product. It should be fine.
if (answer == d20.get(i)) // If the combo is equal the d20 roll
System.out.println("Solution"); // Print solution
else
System.out.println("No Solution"); // Otherwise print no solution
rolls.subList(0, 5).clear(); // Clears out the first 5 elements to make coding easier
answer = 0; // Reset the answer var
System.out.println(record);
} // End For loop
} // End main
} // End class
It's set up so that the user can do the rolls more than once, if they were to try this game 3 times, they can do all three then get all three answers at once.
If you want to see it in a different way, here's the pastebin: http://pastebin.com/PRB0NKpN
edit 2: Here's my final solution. A bit bruce-forcey.
import java.util.ArrayList;
import java.util.Scanner;
public class testClass {
public static void main(String[] args) {
ArrayList<Integer> d20 = new ArrayList<Integer>();
ArrayList<Integer> rolls = new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
d20.add(sc.nextInt());
rolls.add(sc.nextInt());
rolls.add(sc.nextInt());
rolls.add(sc.nextInt());
rolls.add(sc.nextInt());
rolls.add(sc.nextInt());
}
int num1 = 0, num2 = 0, num3 = 0, num4 = 0;
for (int x = 0; x < d20.size(); x++) {
int wright = 0, rong = 0;
for (int i = 1; i < 4; i++) {
for (int j = 1; j < 4; j++) {
for (int k = 1; k < 4; k++) {
for (int m = 1; m < 4; m++) {
if (i == 1) {
num1 = rolls.get(0) + rolls.get(1);
} else if (i == 2) {
num1 = rolls.get(0) - rolls.get(1);
} else if (i == 3) {
num1 = rolls.get(0) * rolls.get(1);
}
if (j == 1) {
num2 = num1 + rolls.get(2);
} else if (j == 2) {
num2 = num1 - rolls.get(2);
} else if (j == 3) {
num2 = num1 - rolls.get(2);
}
if (k == 1) {
num3 = num2 + rolls.get(3);
} else if (k == 2) {
num3 = num2 - rolls.get(3);
} else if (k == 3) {
num3 = num2 * rolls.get(3);
}
if (m == 1) {
num4 = num3 + rolls.get(4);
} else if (m == 2) {
num4 = num3 - rolls.get(4);
} else if (m == 3) {
num4 = num3 * rolls.get(4);
}
if (d20.get(x) == num4) {
wright = 1;
}
}
}
}
}
if (wright == 1)
System.out.println("Case " + (x+1) + ": Solution");
else
System.out.println("Case " + (x+1) + ": No Solution");
rolls.subList(0, 5).clear();
}
}
}
I see you find answer by yourself, but I also tried to solve your problem, and I decide to post here an another solution in any case:
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
public static void main(String[] args){
Test test = new Test();
test.combineOperators();
Scanner scanner = new Scanner(System.in);
int result = scanner.nextInt(); //get input
int[] numbers = new int[5];
for(int i = 0; i <5; i++){
numbers[i] = scanner.nextInt();
}
ArrayList<Integer> results = test.operationsOnArrays(numbers, test.combineOperators()); //check for results
if(results.contains(result)){
System.out.println(result + " is a possible solution");
}else{
System.out.println(result + " is not a possible solution");
}
}
public ArrayList<String[]> combineOperators(){ //create all possible combinations of operators
String[] signs = {"+","-","*"};
ArrayList<String[]> combinations = new ArrayList<String[]>();
for(String a : signs){
for (String b : signs){
for(String c : signs){
for(String d: signs){
String[]temp = {a,b,c,d};
combinations.add(temp);
}
}
}
}
return combinations;
}
public ArrayList operationsOnArrays(int[] num, ArrayList<String[]> combinations){ //do the math with every combination on given ints
ArrayList<Integer> list = new ArrayList<Integer>();
for(String[] operators : combinations){ //for every operators combination
int result = num[0];
for(int i = 0; i<=3 ; i++){
result = doTheMath(operators[i],result,num[i+1]); // take two ints and operator
}
list.add(result);
}
return list;
}
public int doTheMath(String operator, int prev, int next){ // it take two ints from input array, and do operation
if(operator.equals("+")){ // determined by a taken operator
return prev + next;
}else if(operator.equals("-")){
return prev - next;
}else if(operator.equals("*")){
return prev *next;
}
return 0;
}
}
I think that this way, it is vary simple to expand, for more numbers or operator, or even to implement reordering of input numbers.

Having trouble with a while loop that gets a certain series of numbers from an input

I'm trying to half the input if it % 12 == 0, but if it isn't then you multiply it by 3 and add 1 onto the sum.
The question that I'm working off is: http://i.imgur.com/VzuPtZJ.png
With the code I have currently(which is below), if I enter 12, like in the question I start off with 6, but then the results begin to go wrong and then they go insanely wrong with values in the millions and negative millions etc.
import java.util.*;
public class sheet12t3
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int aNumber = Integer.parseInt(in.nextLine());
hailstone(aNumber);
}
public static void hailstone(int x)
{
int count = 1;
int max = 0;
String results = "Hailstone series for the number " + x + " is ";
while (x >= 1)
{
if (x % 12 == 0)
x = x / 2;
else
x = 3 * x + 1;
count++;
results += + x + ", ";
if (x > max)
max = x;
}
results += "a total of " + count + " numbers in this sequence with a maximum value of " + max;
System.out.print(results);
}
}
The question says divide by two if the number is even. But you divide by 2 only when it is dividable by 12.
Change this line
(x % 12 == 0)
to
(x % 2 == 0)
And change while (x >= 1) to while (x > 1)
Here is the code you are looking for:-
import java.util.*;
public class sheet12t3
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int aNumber = Integer.parseInt(in.nextLine());
hailstone(aNumber);
}
public static void hailstone(int x)
{
int count = 1;
int max = 0;
String results = "Hailstone series for the number " + x + " is ";
while (x > 1)
{
if (x % 2 == 0)
x = x / 2;
else
x = 3*x + 1;
System.out.print(x+" ");
max++;
}
}
}

3n + 1 failed for unknown reason

I am doing the programming challenges of which I am doing the 3n + 1 challenge. I ahve completed code for it and it works fine for me completely BUT on the website it keeps saying that I have the wrong answer.I have no idea why if anyone can give me a reason for this it would be a great help. Code is below.
import java.util.*;
import java.io.*;
class Conjecture {
public static void main(String[] args) throws IOException {
int array[] = new int[8];
int finalCounter = 0;
int currentCounter = 0;
Scanner scanner = null;
try {
scanner = new Scanner(
new BufferedReader(new FileReader("text.txt")));
int counter = 0;
while (scanner.hasNext()) {
array[counter] = scanner.nextInt();
counter++;
}
} finally {
if (scanner != null) {
scanner.close();
System.out.println("done");
}
}
for (int loop = 0; loop < array.length; loop += 2) {
int i = array[loop];
int j = array[loop + 1];
finalCounter = 0;
for (int k = i; k < j; k++) {
int x = k;
currentCounter = 0;
while (x != 1) {
if (x % 2 == 0) {
x = x / 2;
currentCounter++;
} else if (x % 2 == 1) {
x = x * 3 + 1;
currentCounter++;
}
if (currentCounter > finalCounter) {
finalCounter = currentCounter;
}
}
}
System.out.println(i + " " + j + " " + (finalCounter + 1));
}
}
}
Instead of reading from file.txt, you should read the input from System.in. Since the problem statement does not says the number of test cases, you should process each case at the moment of reading the case. Your array is just 8 elements long, and I'm pretty sure there is going to be more test cases.

Categories