Java Thread

Troncoso

VIP Member
meant to say, two arrays being used. :eek:

anyways, you're going to have to mod it for your own use obviously, but it might be of some use to you.
Code:
import java.util.*;

public class Permutation {

	public ArrayList<String> getPerms(String s) {

		ArrayList<String> list = new ArrayList<String>();
		if (s.length() == 1)
			list.add(s);
		else {
			for (int i = 0; i < s.length(); i++) {
				char x = s.charAt(i);
				String y = "";
				for (int j = 0; j < s.length(); j++) {
					if (i != j)
						y += s.charAt(j);
				}
				ArrayList<String> results = getPerms(y);
				for (String sf : results) {
					list.add(x + sf);
				}

			}
		}
		return list;

	}

	public static void main(String[] ar) {
		for (String s : new Permutation().getPerms("abcdefg")) {
			System.out.println(s);
		}
	}
}

So this is pretty much taking a string of characters and returning every possible order you could put them in?
Not exactly what I'm doing, but I could definitely see that as an approach to my problem.
 

Cromewell

Administrator
Staff member
You are missing some letters (Q and Z), but that may be intentional.

My first thought was I would probably approach this with a jagged array. The index of first level is the number pressed - 1 (0 indexed) and then you just need to figure out the recursion to loop through each segment to get all combinations.

The array would be like:
Code:
Character keypad = {{'a','b','c'},{'d','e','f'},{'g','h','i'},{'j','k','l'},{'m','n','o'},{'p','q','r','s'},{'t','u','v'},{'w','x','y','z'}}
And the recursion (you could probably do it with some loops and some cleverness), I'll leave to you :p
 

Troncoso

VIP Member
You are missing some letters (Q and Z), but that may be intentional.

My first thought was I would probably approach this with a jagged array. The index of first level is the number pressed - 1 (0 indexed) and then you just need to figure out the recursion to loop through each segment to get all combinations.

The array would be like:
Code:
Character keypad = {{'a','b','c'},{'d','e','f'},{'g','h','i'},{'j','k','l'},{'m','n','o'},{'p','q','r','s'},{'t','u','v'},{'w','x','y','z'}}
And the recursion (you could probably do it with some loops and some cleverness), I'll leave to you :p

Yeah, I mentioned that they were intentionally left out. The recursion is what's throwing me off. I understand it, but it's a strange subject and I find it hard to work with, especially with something like this.
 

Cromewell

Administrator
Staff member
Yeah, I mentioned that they were intentionally left out. The recursion is what's throwing me off. I understand it, but it's a strange subject and I find it hard to work with, especially with something like this.

Sorry I missed that in your original post. I have an idea of how to make it work but I need to get my dev machine running, hopefully I'll post back shortly. :)
 

Troncoso

VIP Member
Sorry I missed that in your original post. I have an idea of how to make it work but I need to get my dev machine running, hopefully I'll post back shortly. :)

That would be really cool. Anything and everything around this is no issue so far, but I can't continue until I've done this much. haha.
 

Cromewell

Administrator
Staff member
I keep getting hung up on the wrong approach, everytime I try to change it I end up with a longer batch of code that is the same junk I got rid of. I know exactly what I need to do but for some reason I can't put it into code correctly.

I'm going to have to come back to this or I might go crazy. Sometimes sleeping on it helps a lot. You come back and are like 'what was I thinking this is easy.' :p
 

Troncoso

VIP Member
I keep getting hung up on the wrong approach, everytime I try to change it I end up with a longer batch of code that is the same junk I got rid of. I know exactly what I need to do but for some reason I can't put it into code correctly.

I'm going to have to come back to this or I might go crazy. Sometimes sleeping on it helps a lot. You come back and are like 'what was I thinking this is easy.' :p

I've tried that a couple times. Haha. But it's still throws me for a loop.
 

NyxCharon

Active Member
Is this what you're looking for?
Code:
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author NyxCharon
 */
public class Telephone 
{
    private static final String[][] maps = 
    {{"0"},{"1"},
    {"A","B","C"}, 
    {"D","E","F"}, 
    {"G","H","I"},
    {"J","K","L"}, 
    {"M","N","O"}, 
    {"P","R","S"},
    {"T","U","V"}, 
    {"X","Y","W"}};
   

  

    public static List getConditions(String number) 
    {
        if (number.startsWith("0") || number.startsWith("1")) {
            return new ArrayList();
        }

        List list = new ArrayList();

        int[] arr = new int[number.length()];
        for (int j = 0; j < arr.length; j++) {
            arr[j] = Integer.parseInt(String.valueOf(number.charAt(j)));
        }
        combine("", arr, 0, list);
        return list;
    }

    public static void combine(String a, int[] number, int current,List list) 
    {
        for (int k = 0; k < maps[number[current]].length; k++) 
        {
            if (current == number.length - 1) 
                 list.add(a + maps[number[current]][k]);
            else 
                combine(a + maps[number[current]][k], number, current + 1,list);
        }
    }
    public static void main(String[] args)
    {
        List l=getConditions("4456789");
        for(int i=0;i<l.size();i++)
            System.out.println(l.get(i));
    }
}
 

Cromewell

Administrator
Staff member
Yeah that's like what I was trying to do. For some reason I kept making a bunch of for loops even through I knew it was wrong. And if you add typing to your list it wont generate compiler warnings :p
 

Troncoso

VIP Member
Is this what you're looking for?
Code:
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author NyxCharon
 */
public class Telephone 
{
    private static final String[][] maps = 
    {{"0"},{"1"},
    {"A","B","C"}, 
    {"D","E","F"}, 
    {"G","H","I"},
    {"J","K","L"}, 
    {"M","N","O"}, 
    {"P","R","S"},
    {"T","U","V"}, 
    {"X","Y","W"}};
   

  

    public static List getConditions(String number) 
    {
        if (number.startsWith("0") || number.startsWith("1")) {
            return new ArrayList();
        }

        List list = new ArrayList();

        int[] arr = new int[number.length()];
        for (int j = 0; j < arr.length; j++) {
            arr[j] = Integer.parseInt(String.valueOf(number.charAt(j)));
        }
        combine("", arr, 0, list);
        return list;
    }

    public static void combine(String a, int[] number, int current,List list) 
    {
        for (int k = 0; k < maps[number[current]].length; k++) 
        {
            if (current == number.length - 1) 
                 list.add(a + maps[number[current]][k]);
            else 
                combine(a + maps[number[current]][k], number, current + 1,list);
        }
    }
    public static void main(String[] args)
    {
        List l=getConditions("4456789");
        for(int i=0;i<l.size();i++)
            System.out.println(l.get(i));
    }
}

I love you and I hate you. Haha. That's exactly what I need. But, gah. That freaking recursion. I just can't get a handle on it enough to implement it.
Like, I understand what it is and how to use it. But I have a hard time envisioning how it's going to produce the results I want.

Though, I didn't need the 0 or 1 check at the beginning. It's assumed that those will never be entered. But, that's a simple fix. I really appreciate this. I've been racking my brain for a couple days now.
 
Last edited:

Dan-987

New Member
Struggling Programming Student - Advice/support needed.

Hi Guys,

Havent really used this forum much, just wanted to bring up a personal problem thats been hanging over me. Basically I have fallen majorly behind on my programming course. I know some programming basics like classes, objects, variables, methods, loops. However due to some personal issues fell behind, the class are now on Inheritance and GUI's.

I have exams on this in about 8 weeks time, do you reckon it would be possible for someone with no/very little programming knowledge to catch up in about 6-7 weeks. If I do about 10-15 hours a week?

Some support/backing from people who know what they are talking about, or been in a similar position please respond asap. Advice and comments would really help me out.

Many thanks,
Dan :)
 

Troncoso

VIP Member
Struggling Programming Student - Advice/support needed.

Hi Guys,

Havent really used this forum much, just wanted to bring up a personal problem thats been hanging over me. Basically I have fallen majorly behind on my programming course. I know some programming basics like classes, objects, variables, methods, loops. However due to some personal issues fell behind, the class are now on Inheritance and GUI's.

I have exams on this in about 8 weeks time, do you reckon it would be possible for someone with no/very little programming knowledge to catch up in about 6-7 weeks. If I do about 10-15 hours a week?

Some support/backing from people who know what they are talking about, or been in a similar position please respond asap. Advice and comments would really help me out.

Many thanks,
Dan :)

Your original thread was fine. This thread is for specific Java programming help.
 

massahwahl

VIP Member
I apologize if its already been asked, but if I were interested in learning how to code java are there any sites you guys recommend?
 

zombine210

New Member
thenewboston.com

That links to thenewboston's beginner Java tutorials. On the site, you will also find advanced and game oriented tutorials. Not to mention several for other languages.

thenewboston videos are ok to review material you already know, but useless beyond that. the guy is not a very good teacher, he uses unconventional identifier names, rarely uses correct terminology, and is overall mediocre. i did watch about 40+ of his videos, so i know.
 
Last edited:

Troncoso

VIP Member
thenewboston videos are ok to review material you already know, but useless beyond that. the guy is not a very good teacher, he uses unconventional identifier names, rarely uses correct terminology, and is overall mediocre. i did watch about 40+ of his videos, so i know.

Yeah, I've watched his videos too, and I learned a lot from them.
Yeah, he's not very conventional, but he knows his stuff and he explains it well. I guess it's just a matter of opinion, but a lot of people appreciate what he does and learns well from it.
 

Troncoso

VIP Member
I'm playing with threads. This program is suppose to add/subtract a random number until the total is exactly 1000. Though, because of the nature of threads, the output is in correct, and sometimes it stops on something besides 1000. How would I fix that?

Source code:

Code:
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;

import java.util.Random;
import java.util.Scanner;

public class Threads {

    public static void main(String[] args) { 
       new Threads().go();
    }
    
    int number;
    
    public Threads() {
        number = 0;
    }
    
    public void go() {
        ExecutorService ex = Executors.newCachedThreadPool();
        Calc calc1 = new Calc(1);
        Calc calc2 = new Calc(2);
        Calc calc3 = new Calc(3);
        
        System.out.println ("This program adds and subtracts randomly.");
        System.out.println ("It ends when it calculates 1000.");
        System.out.println ("Press enter to start.\n");
        new Scanner(System.in).nextLine();
       
        while (number != 1000) {
            ex.execute(calc1);
            ex.execute(calc2);
            ex.execute(calc3);        
        }
        
        ex.shutdown();
    }
    
    private class Calc implements Runnable{
        int name;
        
        public Calc(int name) {
            this.name = name;
        }
                
        public synchronized void run() {
            Random rand = new Random (System.currentTimeMillis());
            int num = rand.nextInt(99) + 1;
            if (Threads.this.number < 1000) {
                Threads.this.number += num;
                System.out.printf ("Player %d adds %d to get %d\n", name, num, Threads.this.number);
            }
            else if (Threads.this.number > 1000) {
                Threads.this.number -= num;
                System.out.printf ("Player %d subtracts %d to get %d\n", name, num, Threads.this.number);
            }
        }
    }
}
 

NyxCharon

Active Member
I'm playing with threads. This program is suppose to add/subtract a random number until the total is exactly 1000. Though, because of the nature of threads, the output is in correct, and sometimes it stops on something besides 1000. How would I fix that?

It's the nature of threads, sometimes a thread gets interrupted and uses a old value instead of the "real" value, It's called the race condition.

You need to implement a lock object to fix it.
An example for a bank account class:
Code:
balancelock.lock();
try
{
//code for the thread to do
}
finally
{
balancelock.unlock();
}

obviously, some stuff is missing there, but you should get the idea. You HAVE to have the finally, because if a exception gets thrown, you won't ever unlock the object and the program, well will lock. So look up the lock class and some examples. :good:
 

Troncoso

VIP Member
It's the nature of threads, sometimes a thread gets interrupted and uses a old value instead of the "real" value, It's called the race condition.

You need to implement a lock object to fix it.
An example for a bank account class:
Code:
balancelock.lock();
try
{
//code for the thread to do
}
finally
{
balancelock.unlock();
}

obviously, some stuff is missing there, but you should get the idea. You HAVE to have the finally, because if a exception gets thrown, you won't ever unlock the object and the program, well will lock. So look up the lock class and some examples. :good:

Damn you....I knew there was a reason my professor went into restraint locks and whatnot before talking about threads. Haha. I should have thought about that.

Edit: It turned out, all I needed to do, was to put Thread.sleep(10), between the thread executions.
 
Last edited:

NyxCharon

Active Member
Edit: It turned out, all I needed to do, was to put Thread.sleep(10), between the thread executions.

That's not really the proper way to do it, to be honest. It might seem to fix it, and you might not notice the problem, but it's probably still there. A lock is the proper way to do it. The general rule I was told was that if you manipulate the same object/var/whatever, use a lock.

Also, I hope you at least catch for a interrupted exception with that sleep call.
 
Top