F(n):
if n >= 6:
F(n/3)
F(2*n/3)
print n
How would I turn this into a nonrecursive function? ive tried to use two while loops one for the n/3 case and one for the 2*n/3 case but nothing outputs the right things
public static void F2Stack(int n) {
Stack stack2 = new Stack();
int current = n;
int current2 = n;
while(current >= 6) {
current = current/3;
stack2.push(current);
}
while(current2 >= 6) {
current2 = current2*2/3;
stack2.push(current2/3);
stack2.push(current2*2/3);
stack2.push(current2);
}
while(!(stack2.isEmpty())){
System.out.println(stack2.pop());
}
}
Damn Corono Virus Lockdown! it took four or five hours today, but we got something. The hard part was java is not capable to do "go to label" I guess. Only you can do "continue/break label". Anyway hope this helps someone;
public static void main(String[] args) {
System.out.println("vvvv 18 recursive vvvv");
recursive(18);
System.out.println("vvvv 18 nonrecursive vvvv");
nonRecursive(18);
System.out.println("vvvv 25 recursive vvvv");
recursive(25);
System.out.println("vvvv 25 nonrecursive vvvv");
nonRecursive(25);
System.out.println("vvvv 31 recursive vvvv");
recursive(25);
System.out.println("vvvv 31 nonrecursive vvvv");
nonRecursive(25);
}
static void doJob(int n) {
System.out.println(n);
}
static void recursive(int number) {
if (number >= 6) {
recursive(number/3);
recursive(2*number/3);
}
doJob(number);
}
static void nonRecursive(int number) {
// a basic context
class Ctx {
int n, m;
boolean bn, bm;
public Ctx(int num) {
n = num / 3;
// do not try m = 2 * n :)
m = 2 * num / 3;
}
};
// how many times can we change the context?
// we will use here a bit math
int d = 2 * ((int)(Math.log(2 * number)/Math.log(3)) + 1);
Ctx[] ctx = new Ctx[d];
// current context
ctx[0] = new Ctx(number);
int i = 0;
while (number >= 6 && ctx[0] != null) {
// do n/3
if (ctx[i].n >= 6 && !ctx[i].bn) {
i++;
ctx[i] = new Ctx(ctx[i-1].n);
continue;
}
// we reached as deep as poosible for n/3
if (!ctx[i].bn) {
doJob(ctx[i].n);
ctx[i].bn = true;
}
// now do 2*n/3
if (ctx[i].m >= 6 && !ctx[i].bm) {
i++;
ctx[i] = new Ctx(ctx[i-1].m);
continue;
}
if (!ctx[i].bm) {
doJob(ctx[i].m);
ctx[i].bm = true;
}
// we are done with this context
ctx[i] = null;
if (i > 0) {
i--;
if (!ctx[i].bn) {
doJob(ctx[i].n);
ctx[i].bn = true;
} else if (!ctx[i].bm) {
doJob(ctx[i].m);
ctx[i].bm = true;
}
}
}
doJob(number);
}
Related
As I have already made the code just I have to add the required condition(1000 == 1 ! 0001). Can anybody help me out.
public class ReverseNum {
static void reverseInteger(int n) {
// Write your code here
if (n <= 0) {
System.out.print("-");
reverseInteger(n * -1);
} else if (n < 10) {
System.out.println(n);
}
else {
System.out.print(n % 10);
reverseInteger(n / 10);
}
}
public static void main (String args[]){
Scanner s = new Scanner(System.in);
int num = s.nextInt();
reverseInteger(num);
}
}
Be careful with negative numbers: they need special consideration (and also will break string reversal and parsing).
A solution that works with any int:
public static int reverse(int value) {
if (value < 0) {
// special handling for negative numbers
return 0 - reverse(-value);
}
int reversed = 0;
while (value > 0) {
reversed = reversed * 10 + (value % 10);
value /= 10;
}
return reversed;
}
Test cases:
assertEquals(0, reverse(0));
assertEquals(321, reverse(123));
assertEquals(98765, reverse(567890000));
assertEquals(-91, reverse(-19));
assertEquals(-2, reverse(-20000));
Try this code :
private static int reverseInteger(int n) {
if (n == 0) {
return n;
}
int symbol = n / Math.abs(n);
n = Math.abs(n);
String str = new StringBuilder(String.valueOf(n)).reverse().toString();
return symbol * Integer.parseInt(str);
}
Test cases:
#Test
public void test_reverseInteger() {
assertEquals(0, reverseInteger(0));
assertEquals(321, reverseInteger(123));
assertEquals(98765, reverseInteger(567890000));
assertEquals(-91, reverseInteger(-19));
assertEquals(-2, reverseInteger(-20000));
}
Using the following input string * + 16 4 + 3 1 and these instructions:
A prefix expression is where the operator comes first. For example, +
5 7 would be 12.
I am able to successfully generate the expected output of 80 with my current code, which I will post below. However, with another input string * + 16 * + 16 4 + 3 1 + 3 1 my output is 576, where it is expected to be 384. I'm not quite sure where I went wrong with my algorithm.
public class QueueUtils {
public static Queue<String> build(String line) {
Queue<String> queue = new LinkedList<>();
Scanner scanner = new Scanner(line);
while (scanner.hasNext())
{
String token = scanner.next();
queue.add(token);
}
return queue;
}
public static int eval(Queue<String> s)
{
List<String> list = new ArrayList<>(s);
List<String> operators = new ArrayList<>();
operators.add("+");
operators.add("-");
operators.add("*");
int n = eval(list, operators);
return n;
}
private static Integer eval(List<String> list, List<String> operators)
{
for (int i = 0; i < list.size(); i++)
{
String current = list.get(i);
String prev = null;
String next = null;
String nextNext = null;
if (i != 0)
{
prev = list.get(i - 1);
}
if (i != list.size() - 1)
{
next = list.get(i + 1);
}
if (i < list.size() - 2)
{
nextNext = list.get(i + 2);
}
if (operators.contains(prev) && prev != null)
{
if (!operators.contains(current)) {
int a = Integer.parseInt(current);
if (!operators.contains(next) && next != null) {
int b = Integer.parseInt(next);
Integer result = doOperation(prev, a, b);
list.remove(current);
list.remove(next);
list.add(i, result.toString());
eval(list, operators);
}
if (next == null)
{
list.remove(prev);
}
}
else
{
if (!operators.contains(next))
{
if (operators.contains(nextNext))
{
list.remove(current);
eval(list, operators);
}
}
}
}
else
{
if (operators.contains(current))
{
if (!operators.contains(next))
{
if (operators.contains(nextNext) || nextNext == null)
{
if (prev != null)
{
list.remove(current);
eval(list, operators);
}
}
}
}
}
}
return Integer.parseInt(list.get(0));
}
private static int doOperation(String operator, int a, int b)
{
int n = 0;
if (operator.equals("+"))
{
n = a + b;
}
else if (operator.equals("-"))
{
n = a - b;
}
else if (operator.equals("*"))
{
n = a * b;
}
return n;
}
}
Calling code:
public class Demo2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an expression in prefix form (operator comes first)");
String line = keyboard.nextLine();
Queue<String> q = QueueUtils.build(line);
int result = QueueUtils.eval(q);
System.out.println(result);
}
}
So in order to solve this you need first need to reverse your input (so * + 16 * + 16 4 + 3 1 + 3 1 will become 1 3 + 1 3 + 4 16 + * 16 + *) and then use a bit of recursion to work your operations in groups of three.
So
1 3 + 1 3 + 4 16 + * 16 + *
4 4 20 * 16 + *
4 [80 16 + *] // we can't do anything with 4 4 20, so we just move on one.
4 [96 *]
4 96 *
384
Here's the code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class InputFunction {
private int doOperation(int a, int b, String operator) throws Exception {
int result;
if("+".equals(operator)){
result = a + b;
} else if("-".equals(operator)){
result = a - b;
} else if("*".equals(operator)){
result = a * b;
} else {
throw new Exception("Unsupported operator \"" + operator + "\"");
}
return result;
}
private List<String> evaluate(List<String> function) throws Exception {
List<String> processed = new ArrayList<>();
if(function.size() <= 2) {
return function;
} else {
for (int i = 0; i < function.size(); i += 3) {
String a = function.get(i);
if ((i + 1) < function.size()) {
String b = function.get(i + 1);
if ((i + 2) < function.size()) {
String c = function.get(i + 2);
if (a.matches("\\d+") && b.matches("\\d+") && !c.matches("\\d+")) {
processed.add(String.valueOf(doOperation(Integer.valueOf(a), Integer.valueOf(b), c)));
} else {
processed.add(a);
if(c.matches("\\d+")) {
processed.addAll(evaluate(function.subList(i + 1, function.size())));
break;
} else {
processed.add(b);
processed.add(c);
}
}
} else {
processed.add(a);
processed.add(b);
}
} else {
processed.add(a);
}
}
}
return evaluate(processed);
}
private void doFunction(String input) throws Exception{
List<String> function = Arrays.asList(input.split(" "));
Collections.reverse(function);
System.out.println(evaluate(function));
}
public static void main(String ... args) {
InputFunction inputFunction = new InputFunction();
try {
inputFunction.doFunction("+ + 5 5 + 5 5");
inputFunction.doFunction("* + 16 * + 16 4 + 3 1 + 3 1");
} catch (Exception e) {
e.printStackTrace();
}
}
}
... admit-ably I've not tried with any examples with a "-", but you should get the idea.
I know it is a bit too late to answer this, but the answer given does not contain any stacks or queues, and the assignment requires that you use them. so here it is:
public static int eval(Queue<String> s){
Stack<String> list = new Stack<>();
Stack<Integer> saved = new Stack<>();
list.addAll(s);
while(!list.isEmpty()){
String val = list.pop();
if(val.equals("+") || val.equals("-") || val.equals("*")){
if(val.equals("+")){
saved.add((saved.pop() + saved.pop()));
}
if(val.equals("-")){
saved.add((saved.pop() - saved.pop()));
}
if(val.equals("*")){
saved.add((saved.pop() * saved.pop()));
}
}else{
saved.add(Integer.parseInt(val));
}
}
return saved.pop();
}
I'm having some trouble with my programming exercise in which I should implement dequeues using arrays.
I already got the operations I need but after the implementation you should run through the numbers 1-20 and insert the even numbers at the end of the dequeue and the odd numbers add the beginning.
After that you should use the method removeFront to remove all numbers in the list and should print them on the console.
There is also the hint that the correct output is: (19,17,15...,1,2,4,...,20).
My problem now is that the number 1 is missing in the list and instead it prints out a null value as the first item to be removed.
public class Dequeues<E> {
private final int max;
private int head;
private int tail;
private E[] deque;
private int counter;
public Dequeues(int max) {
this.max = max;
deque = (E[]) new Object[max];
this.head = 0;
this.tail = 0;
this.counter = 0;
}
public boolean isEmpty (){
return (counter == 0);
}
public boolean isFull() {
return(counter>= max);
}
public void addFront (E x){
if(!isFull()) {
if (head == 0) {
head = deque.length-1;
deque[head] = x;
} else {
deque[head--] = x;
}
counter++;
}
else throw new IndexOutOfBoundsException("Stack is full!");
}
public void addBack(E x){
if(!isFull()) {
if(tail == deque.length-1) {
tail = 0;
deque[tail] = x;
} else {
deque[tail++] = x;
}
counter++;
}
else throw new IndexOutOfBoundsException("Stack is full!");
}
public E removeFront(){
if(!isEmpty()) {
E ret = deque[head];
deque[head++] = null;
if(head >= deque.length) {
head = 0;
}
counter--;
return ret;
}
else throw new IndexOutOfBoundsException("Stack is empty");
}
public E removeBack(){
if (!isEmpty()) {
E ret = deque[tail];
deque[tail--] = null;
if(tail < 0) {
tail = deque.length-1;
}
counter--;
return ret;
}
else throw new IndexOutOfBoundsException("Stack is empty");
}
public static void main (String [] args) {
Dequeues test = new Dequeues(20);
for (int i = 1; i <= test.deque.length; i++) {
if(i % 2 == 0) {
test.addBack(i);
} else if(i % 2 == 1) {
test.addFront(i);
}
}
System.out.println("Use of removeFront and output of the values: ");
for (int i = 0; i < test.deque.length; i++) {
System.out.print(test.removeFront() + " ");
}
}}
Output is the following:
Use of removeFront and output of the values:
null 19 17 15 13 11 9 7 5 3 2 4 6 8 10 12 14 16 18 20
You just simply wrong used -- operator.
Right implementation of the addFront method should be:
public void addFront (E x){
if(!isFull()) {
if (head == 0) {
head = deque.length-1;
deque[head] = x;
} else {
deque[--head] = x;
}
counter++;
}
else throw new IndexOutOfBoundsException("Stack is full!");
}
So, the difference is here deque[--head] = x;
--head means reduce head value by one and then use it.
head-- means use value head and then reduce its value
Your situation was:
head = deque.length-1; head == 19
head != 0 and you go to the else statement. head value = 19. You used head-- and got again 19 and decremented it by one, but had to use --head.
So i have to make a method that will return a value based on m or M in a string. so far i have this
public static int mIndex(String x) {
if (x.indexOf('M') >= 0) {
return x.indexOf('M');
}
if (x.indexOf('m') >= 0) {
return x.indexOf('m');
} else {
return -1;
}
}
The problem is that it only returns M if it is first in the String. Is there anyway for it to detect m or M, and then give a value based on that?
For something like that, a regular expression is your friend:
public static int mIndex(String x) {
Matcher m = Pattern.compile("[mM]").matcher(x);
if (m.find())
return m.start();
return -1;
}
Test
System.out.println(mIndex("kamdkMMM"));
System.out.println(mIndex("KAMDKmmm"));
System.out.println(mIndex("Hello World"));
Output
2
2
-1
Try this:
String s = "MarshmallowmmMaM";
System.out.println("Index of 'M':");
int index = s.indexOf("M");
while (index >= 0) {
System.out.println(index);
index = s.indexOf("M", index + 1);
}
System.out.println("Index of 'm':");
index = s.indexOf("m");
while (index >= 0) {
System.out.println(index);
index = s.indexOf("m", index + 1);
}
Output:
Index of 'M':
0
13
15
Index of 'm':
5
11
12
If you want to detect the first position of each case for letter M. "upper&lower".
public class Main {
public static int M_POSITION = -1;
public static int m_POSITION = -1;
public static void mIndex(String x) {
int i = 0;
while (i < x.length()) {
if (x.charAt(i) == 'M') {
if (M_POSITION == -1)
M_POSITION = i;
} else if (x.charAt(i) == 'm') {
if (m_POSITION == -1)
m_POSITION = i;
}
++i;
}
}
public static void main(String[] args) {
mIndex("adsm");
System.out.println(m_POSITION);
System.out.println(M_POSITION);
}
}
Herro, Um I'm not sure if this is how you use this site but uh lets get to it... So I need help on this project and I have to do this -
Input [][] Output
A - F -> Multiply by 3, Divide by 4
G - J -> Divide by 3 + 25
K - N -> Find Greatest Factor * 2
O - Q -> Find largest prime inclusive * 3
R - W -> Find Smallest Factor Except 1
X - Z -> Sum Numbers
So I was wondering if my first couple is correct, and need help on the empty space. So the Letter represents the number of the as in "Z" is the last letter so its 26, and "A" is the first so its 1. So if an responses... Thanks ! package Fun;
import java.util.Scanner;
public class Fun {
public static void main(String[] args) {
// TODO Auto-generated method stub
run();
}
public static void run()
{
input();
evaluateAlphabet();
evaluate();
}
public static void input()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Letter, please");
x = sc.next();
}
public static String x = " ";
public static int temp = 0;
public static int answer = 0;
public static void evaluateAlphabet()
{
if(x.equals("A"))
{
temp = 1;
}
else if (x.equals("B"))
{
temp = 2;
}
else if (x.equals("C"))
{
temp = 3;
}
else if (x.equals("D"))
{
temp = 4;
}
else if (x.equals("E"))
{
temp = 5;
}
else if (x.equals("F"))
{
temp = 6;
}
else if (x.equals("G"))
{
temp = 7;
}
else if (x.equals("H"))
{
temp = 8;
}
else if (x.equals("I"))
{
temp = 9;
}
else if (x.equals("J"))
{
temp = 10;
}
else if (x.equals("K"))
{
temp = 11;
}
else if (x.equals("L"))
{
temp = 12;
}
else if (x.equals("M"))
{
temp = 13;
}
else if (x.equals("N"))
{
temp = 14;
}
else if (x.equals("O"))
{
temp = 15;
}
else if (x.equals("P"))
{
temp = 16;
}
else if (x.equals("Q"))
{
temp = 17;
}
else if (x.equals("R"))
{
temp = 18;
}
else if (x.equals("S"))
{
temp = 19;
}
else if (x.equals("T"))
{
temp = 20;
}
else if (x.equals("U"))
{
temp = 21;
}
else if (x.equals("V"))
{
temp = 22;
}
else if (x.equals("W"))
{
temp = 23;
}
else if (x.equals("X"))
{
temp = 24;
}
else if (x.equals("Y"))
{
temp = 25;
}
else if (x.equals("Z"))
{
temp = 26;
}
else if (x.equals("Qwerty"))
{
temp = 27;
}
}
public static void evaluate()
{
if(temp>=1 && temp<= 6)
{
answer = (temp * 3)/4;
System.out.println("Answer is " + answer);
}
else if(temp >= 7 && temp<= 10)
{
answer = (temp/3) + 25;
System.out.println("Answer is " + answer);
}
else if(temp >= 11 && temp<= 14)
{
}
else if(temp>=15 && temp<= 17)
{
for(int i = temp; i>0; i--)
{
for(int j = 2; j <=i/2 + 1; j++)
{
if(i%j==0)
{
break;
}
if(j==i/2 + 1)
{
answer = i * 3;
}
}
}
System.out.println("Answer is " + answer);
}
else if(temp>=18 && temp<= 23)
{
answer = temp;
}
else if(temp>= 24 && temp<=26)
answer = (answer * 12)%26;
System.out.println("Answer is " + answer);
}
}
-Corruption
Here is a better approach for char to int conversion:
Assuming the string has at least 1 character(check for its length), you can get the temp by doing:
temp = x.getCharAt(0) - 'A' + 1;
or, safety first:
temp = 0;
if (x.matches("^[A-Z]{1}$") {
temp = x.getCharAt(0) - 'A' + 1;
}
What's happening here? Every character has an ASCII code, an integer. So, when you have 2 chars and you try to get the distance between them, the result is an int. 'A' - 'A' = 0(that's why i added a + 1), 'B' - 'A' = 1 and so on.
For the if condition, I am using a RegExp. ^ means start of the input, [A-Z]{1} means one of A-Z, $ means the end of the input. So, if it's an A-Z, temp will get a value, anything else won't make it in the if and your temp will remain 0 so you can easily test if you've got an A-Z or not.
That's all for code review, I won't give you solutions, you must work harder, use Google. You won't enjoy and learn if I give you everything ready for a copy paste.