Related
I have found out the solution for standard sudoku however I do not know what to do with sudoku xv.
A Sudoku XV puzzle consists of a standard Sudoku grid with the addition of X and V markers between neighbouring pairs of squares. X markers show all adjacent pairs of squares where the two values in those squares add up to 10, while V markers show all pairs where the two values sum to 5.
I have developed simple sudoku, however, I need help implementing x and v markers between neighbouring pairs of squares
package n.sudoku_cnf;
import java.util.ArrayList;
/**
*
*
*/
public class Sudoku_CNF_Solution {
static final int subN = 3;
static final int N = subN*subN;
static final int N2 = N*N;
static final int VARS = N*N*N;
static int clauses = 0;
static ArrayList<String> DIMACS_CNF = new ArrayList();
static int[] solution = {-1, -2, -3, -4, -5, -6, -7, -8, 9, -10, -11, -12, 13, -14, -15, -16, -17, -18, -19, -20, 21, -22, -23, -24, -25, -26, -27, 28, -29, -30, -31, -32, -33, -34, -35, -36, -37, -38, -39, -40, -41, -42, 43, -44, -45, -46, -47, -48, -49, -50, 51, -52, -53, -54, -55, 56, -57, -58, -59, -60, -61, -62, -63, -64, -65, -66, -67, 68, -69, -70, -71, -72, -73, -74, -75, -76, -77, -78, -79, 80, -81, -82, -83, -84, -85, -86, -87, -88, 89, -90, 91, -92, -93, -94, -95, -96, -97, -98, -99, -100, -101, -102, -103, 104, -105, -106, -107, -108, -109, 110, -111, -112, -113, -114, -115, -116, -117, -118, -119, -120, -121, -122, 123, -124, -125, -126, -127, -128, -129, -130, -131, -132, -133, -134, 135, -136, -137, -138, 139, -140, -141, -142, -143, -144, -145, -146, 147, -148, -149, -150, -151, -152, -153, -154, -155, -156, -157, -158, -159, 160, -161, -162, -163, -164, -165, -166, -167, -168, 169, -170, -171, -172, -173, -174, -175, -176, 177, -178, -179, -180, 181, -182, -183, -184, -185, -186, -187, -188, -189, -190, -191, -192, -193, 194, -195, -196, -197, -198, -199, 200, -201, -202, -203, -204, -205, -206, -207, -208, -209, -210, -211, -212, -213, -214, 215, -216, -217, -218, -219, -220, -221, -222, -223, -224, 225, -226, -227, -228, 229, -230, -231, -232, -233, -234, -235, -236, 237, -238, -239, -240, -241, -242, -243, -244, -245, -246, -247, -248, 249, -250, -251, -252, -253, 254, -255, -256, -257, -258, -259, -260, -261, -262, -263, -264, -265, -266, -267, -268, 269, -270, -271, -272, -273, -274, -275, -276, -277, -278, 279, -280, -281, 282, -283, -284, -285, -286, -287, -288, -289, -290, -291, 292, -293, -294, -295, -296, -297, -298, -299, -300, -301, -302, -303, 304, -305, -306, 307, -308, -309, -310, -311, -312, -313, -314, -315, -316, -317, -318, -319, 320, -321, -322, -323, -324, -325, -326, -327, -328, 329, -330, -331, -332, -333, -334, -335, -336, -337, -338, -339, -340, -341, 342, -343, 344, -345, -346, -347, -348, -349, -350, -351, -352, -353, -354, 355, -356, -357, -358, -359, -360, -361, -362, -363, -364, -365, -366, -367, 368, -369, -370, -371, 372, -373, -374, -375, -376, -377, -378, 379, -380, -381, -382, -383, -384, -385, -386, -387, -388, -389, -390, -391, -392, -393, 394, -395, -396, -397, -398, -399, -400, -401, 402, -403, -404, -405, -406, -407, -408, 409, -410, -411, -412, -413, -414, -415, -416, 417, -418, -419, -420, -421, -422, -423, -424, -425, -426, -427, -428, -429, -430, -431, 432, -433, -434, -435, -436, -437, -438, 439, -440, -441, 442, -443, -444, -445, -446, -447, -448, -449, -450, -451, -452, -453, -454, 455, -456, -457, -458, -459, -460, -461, -462, -463, -464, 465, -466, -467, -468, -469, -470, -471, -472, -473, -474, -475, 476, -477, -478, 479, -480, -481, -482, -483, -484, -485, -486, -487, -488, 489, -490, -491, -492, -493, -494, -495, -496, -497, -498, -499, 500, -501, -502, -503, -504, -505, -506, -507, -508, -509, -510, 511, -512, -513, -514, -515, -516, -517, -518, 519, -520, -521, -522, -523, -524, -525, -526, -527, -528, -529, -530, 531, 532, -533, -534, -535, -536, -537, -538, -539, -540, -541, -542, -543, -544, -545, -546, -547, 548, -549, -550, 551, -552, -553, -554, -555, -556, -557, -558, -559, -560, -561, 562, -563, -564, -565, -566, -567, -568, 569, -570, -571, -572, -573, -574, -575, -576, -577, -578, -579, -580, -581, -582, -583, 584, -585, -586, -587, -588, -589, -590, 591, -592, -593, -594, -595, -596, 597, -598, -599, -600, -601, -602, -603, -604, -605, -606, 607, -608, -609, -610, -611, -612, -613, -614, -615, -616, -617, -618, 619, -620, -621, -622, -623, -624, -625, 626, -627, -628, -629, -630, -631, -632, -633, -634, -635, -636, -637, -638, 639, 640, -641, -642, -643, -644, -645, -646, -647, -648, 649, -650, -651, -652, -653, -654, -655, -656, -657, -658, -659, -660, -661, -662, -663, 664, -665, -666, -667, -668, -669, 670, -671, -672, -673, -674, -675, -676, -677, -678, -679, -680, -681, -682, 683, -684, -685, -686, -687, -688, 689, -690, -691, -692, -693, -694, 695, -696, -697, -698, -699, -700, -701, -702, -703, -704, 705, -706, -707, -708, -709, -710, -711, -712, -713, -714, -715, -716, 717, -718, -719, -720, -721, -722, -723, -724, -725, -726, -727, -728, 729, 0};
/**
* Generate DIMACS CNF format and print any given SAT solution
* #param args the command line arguments
*/
public static void main(String[] args) {
// Generate DIMACS CNF format
addFacts();
atLeastOneDigitInCell();
eachDigitAtMostOnesInRow();
eachDigitAtMostOnesInColumn();
eachDigitAtMostOnesInSubGrid();
print_DIMACS_CNF_format();
// Print a SAT solution
printSATSolutionBoard(solution);
}
/**
*
* #param digit [1...N]
* #param row [1...N]
* #param column [1...N]
* #return
*/
private static int toVariable(int digit, int row, int column){
return (N2*(digit-1) + N*(row-1) + (column-1) + 1);
}
private static void addFacts(){
// Facts
DIMACS_CNF.add("c Pre-assigned entries");
// Update the number of facts according to the number of added DIMACS CNF clauses
int facts=17;
DIMACS_CNF.add(toVariable(3, 2, 6) + " 0");
DIMACS_CNF.add(toVariable(8, 2, 8) + " 0");
DIMACS_CNF.add(toVariable(5, 2, 9) + " 0");
DIMACS_CNF.add(toVariable(1, 3, 3) + " 0");
DIMACS_CNF.add(toVariable(2, 3, 5) + " 0");
DIMACS_CNF.add(toVariable(5, 4, 4) + " 0");
DIMACS_CNF.add(toVariable(7, 4, 6) + " 0");
DIMACS_CNF.add(toVariable(4, 5, 3) + " 0");
DIMACS_CNF.add(toVariable(1, 5, 7) + " 0");
DIMACS_CNF.add(toVariable(9, 6, 2) + " 0");
DIMACS_CNF.add(toVariable(5, 7, 1) + " 0");
DIMACS_CNF.add(toVariable(7, 7, 8) + " 0");
DIMACS_CNF.add(toVariable(3, 7, 9) + " 0");
DIMACS_CNF.add(toVariable(2, 8, 3) + " 0");
DIMACS_CNF.add(toVariable(1, 8, 5) + " 0");
DIMACS_CNF.add(toVariable(4, 9, 5) + " 0");
DIMACS_CNF.add(toVariable(9, 9, 9) + " 0");
clauses += facts;
}
private static void atLeastOneDigitInCell(){
// Every cell contains at least one digit
DIMACS_CNF.add("c Every cell contains at least one digit:");
String str;
for (int row = 1; row <= N; row++) {
for (int column = 1; column <= N; column++) {
str = "";
for (int digit = 1; digit <= N; digit++) {
str += toVariable(digit,row,column) + " ";
}
DIMACS_CNF.add(str + "0");
clauses++;
}
}
}
private static void eachDigitAtMostOnesInRow(){
// Each digit appears at most once in each row
DIMACS_CNF.add("c Each digit appears at most once in each row:");
for (int digit = 1; digit <= N; digit++) {
for (int row = 1; row < N; row++) {
for (int columnLow = 1; columnLow <= N-1; columnLow++) {
for (int columnHigh = columnLow+1; columnHigh <= N; columnHigh++) {
DIMACS_CNF.add("-" + toVariable(digit,row,columnLow) + " -" + toVariable(digit,row,columnHigh) + " 0");
clauses++;
}
}
}
}
}
private static void eachDigitAtMostOnesInColumn(){
// Each number appears at most once in each column
DIMACS_CNF.add("c Each number appears at most once in each column:");
for (int digit = 1; digit <= N; digit++) {
for (int column = 1; column <= N; column++) {
for (int rowLow = 1; rowLow <= N-1; rowLow++) {
for (int rowHigh = rowLow+1; rowHigh <= N; rowHigh++) {
DIMACS_CNF.add("-" + toVariable(digit,rowLow,column) + " -" + toVariable(digit,rowHigh,column) + " 0");
clauses++;
}
}
}
}
}
private static void eachDigitAtMostOnesInSubGrid(){
// Each number appears at most once in each sub-grid
DIMACS_CNF.add("c Each number appears at most once in each sub-grid:");
for(int digit = 1; digit<=N; digit++){
for(int subGridRow = 0; subGridRow <= subN-1; subGridRow++){
for(int subRowLow = 1; subRowLow <= subN-1; subRowLow++){
for(int columnSubGrid = 0; columnSubGrid <= subN-1; columnSubGrid++){
for(int subColumnLow = 1; subColumnLow <=subN; subColumnLow++){
for(int subRowHigh = subRowLow+1; subRowHigh <=subN; subRowHigh++){
for(int subColumHigh = 1; subColumHigh <= subN; subColumHigh++){
if(subColumnLow != subColumHigh){
DIMACS_CNF.add("-" + toVariable(digit,(subN*subGridRow + subRowLow),(subN*columnSubGrid + subColumnLow)) +
" -" + toVariable(digit,(subN*subGridRow + subRowHigh),(subN*columnSubGrid + subColumHigh)) + " 0");
clauses++;
}
}
}
}
}
}
}
}
}
/**
* Print DIMACS CNF format
* #param variables
*/
private static void print_DIMACS_CNF_format(){
// Print DIMACS CNF format
System.out.println("==========================================");
System.out.println("===== Beginning of DIMACS CNF format =====");
System.out.println("==========================================");
System.out.println("c digit range [1..." + N + "]");
System.out.println("c row range: [1..." + N + "]");
System.out.println("c column range: [1..." + N + "]");
System.out.println("c board[digit][row][column]: variable");
for (int digit = 1; digit <= N; digit++) {
for (int row = 1; row <= N; row++) {
for (int column = 1; column <= N; column++) {
System.out.println("c board[" + digit + "][" + row + "][" + column + "]: " + toVariable(digit,row,column));
}
}
}
System.out.println("c #vars: " + VARS);
System.out.println("c #clauses: " + clauses);
System.out.println("p cnf " + VARS + " " + clauses);
for (int i = 0; i < DIMACS_CNF.size(); i++) {
System.out.println(DIMACS_CNF.get(i));
}
System.out.println("====================================");
System.out.println("===== End of DIMACS CNF format =====");
System.out.println("====================================");
System.out.println("");
}
/**
* Print resulting board based on a set of variables from a SAT solution
* #param variables
*/
private static void printSATSolutionBoard(int[] variables){
int digit;
int tmp;
int row;
int column;
int[][] tmpBoard = new int [N][N];
for (row = 0; row < N; row++) {
for (column = 0; column < N; column++) {
tmpBoard[row][column] = -1;
}
}
for (int i = 0; i < variables.length; i++) {
if(variables[i] > 0){
digit = (variables[i]-1)/N2;
tmp = (variables[i]-1)%N2;
row = tmp/N;
column = tmp%N;
tmpBoard[row][column] = digit;
}
}
System.out.println("=======================");
System.out.println("===== Given board =====");
System.out.println("=======================");
for (row = 0; row < N; row++) {
System.out.print(" ");
for (column = 0; column < N; column++) {
System.out.print(((tmpBoard[row][column])>=0? (tmpBoard[row][column]+1):"-") + " ");
}
System.out.println();
}
System.out.println("=======================");
}
}
This question already has answers here:
Java: moving items in array
(6 answers)
Closed 6 years ago.
How to move element of array to specific position on Android JAVA.
We have
int oldPosition, int newPosition
and some like
JSONObject[] tmp = new JSONObject[999];
array of JSONObjects
If you want to just move
tmp[newPosition]=tmp[oldPosition];
Swap
JSONObject jo= tmp[oldPosition];
tmp[oldPosition]=tmp[newPosition];
tmp[newPosition]=jo;
EDIT: There are other ways but you can go through this as well to get your result :)
Exercise : You can understand this logic and use JSONObject type and do necessary changes, Watch out for NullPointerExceptions , handle everything i am lazy to do them
let's say you have int array --> private int array[];
array = new int[]{10,20,30,40,50,60,70,80,90,100};
call this method if you want to swap elements,
swapNumbers(array,9,1);
.
public int[] swapNumbers(int [] arr, int possition1, int possition2){
int temp = arr[possition2];
arr[possition2] = arr[possition1];
arr[possition1] = temp;
System.out.println("array -->" + Arrays.toString(array));
return arr;
}
out put : array[10, 100, 30, 40, 50, 60, 70, 80, 90, 20]
But that doesn't satisfy you?
you need out put to be like this : array[10, 100, 20, 30, 40, 50, 60, 70, 80, 90]
you can use below method
resetUpMyArray(array, array[9],1);
System.out.println("array Finally changed-->" + Arrays.toString(array));
enjoy,
public int[] resetUpMyArray(int[] inputArray, int deleteMeValue,int addMePosition) {
List resultLinkedList = new LinkedList();
for (int itemValue : inputArray)
if (deleteMeValue == itemValue) {
System.out.println("Do not add this value"+itemValue);
} else {
System.out.println("Do add this value "+itemValue +"position-"+deleteMeValue);
resultLinkedList.add(itemValue);
}
System.out.println("array -as new L.L->" + resultLinkedList);
resultLinkedList.add(addMePosition,deleteMeValue);
System.out.println("array -as new L.L all set->" + resultLinkedList);
array = new int[resultLinkedList.size()];
for (int i = 0; i < resultLinkedList.size(); i++) {
array[i] = (int) resultLinkedList.get(i); // Watch out for NullPointerExceptions!
}
return array;
}
Here is two simple algorithm.
Switch values :
switch(array, from, to)
tmp = array[to]
array[to] = array[from]
array[from] = tmp
That will give something like
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
|--<---->--|
[10, 20, 60, 40, 50, 30, 70, 80, 90, 100]
This will simply store the values that will be replace at the index to to be place at index from
Move and shift values:
This one will move one values a shift the values next.
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
|------------^
[10, 20, , 40, 50, 60, 30, 70, 80, 90, 100]
<-----------
[10, 20, 40, 50, 60, 30, 70, 80, 90, 100]
For this, the solution is quite the same, store the values in tmp but shift every value to fill the gap. This code will only work if from < to
tmp = array[to]
i = from
while(i < to)
array[i] = array[i+1]; --Shift the value
i = i + 1
array[to] = tmp;
The goal:
Say I have X workers in a fruit plantation. At the plantation they're growing apples, pears and grapes.
At the end of the day, the foreman grades each workers with a ratio. The total of all ratio's is 100. The ratio is there to determine how to distribute the fruit amongst the workers at the end of the day.
How do I distribute the fruit amongst all workers so that they each get their fair share (within a certain randomness to account for integer division). Only whole fruits are divided, so integer results. And all fruits must be given out.
I'm doing this with about 20 workers, so right now the ratio is in neighbourhood of 0.05 per worker.
What I've tried (pseudo-code):
for each worker:
if applesGiven < appleStock:
worker.give(ratio * applestock);
if pearsGiven < pearStock:
worker.give(ratio * pearStock);
if grapesGiven < grapeStock:
worker.give(ratio * grapeStock);
I would let the exact numer of [fruit] they where given be determined by a boolean Roundup that was initialized with a random boolean and switched after every fruit that was processed.
What I've tried (full-code):
public void balance() {
boolean roundUp = random.nextBoolean();
for (Employee e : employees) {
double ratio = e.getRatio();
if (applePlanned < appleNeeded) {
int apple;
if (roundUp) {
apple = (int) Math.ceil(ratio * appleNeeded);
} else {
apple = (int) Math.floor(ratio * appleNeeded);
}
e.setrapple(apple);
applePlanned += apple;
roundUp = !roundUp;
}
if (pearPlanned < pearNeeded) {
int pear;
if (roundUp) {
pear = (int) Math.ceil(ratio * pearNeeded);
} else {
pear = (int) Math.floor(ratio * pearNeeded);
}
e.setrpear(pear);
pearPlanned += pear;
roundUp = !roundUp;
}
if (grapePlanned < grapeNeeded) {
int grape;
if (roundUp) {
grape = (int) Math.ceil(ratio * grapeNeeded);
} else {
grape = (int) Math.floor(ratio * grapeNeeded);
}
e.setrgrape(grape);
grapePlanned += grape;
roundUp = !roundUp;
}
}
Problems I ran into:
Only about 3/4 of all items are distributed
When I have an even number of fruit, the boolean gets the same value at the start of each new person.
Thank you for looking into this!
Answers in java, python or pseudo-code please, that's what I can read.
Use double math, round down, then randomly hand out the remaining fruit weighted based on ratio. Note, you can make this a lot less ugly with object orientation and loops, but this is a start.
public void distribute(int apple, int pear, int grape) {
double total = apple + pear + grape;
double appleRatio = apple/total;
double pearRatio = pear/total;
double grapeRatio = grape/total;
// apple worker
int appleWorkerApple = (int) (appleRatio*apple);
int appleWorkerPear = (int) (appleRatio*pear);
int appleWorkerGrape = (int) (appleRatio*grape);
// pear worker
int pearWorkerApple = (int) (pearRatio*apple);
int pearWorkerPear = (int) (pearRatio*pear);
int pearWorkerGrape = (int) (pearRatio*grape);
// grape worker
int grapeWorkerApple = (int) (grapeRatio*apple);
int grapeWorkerPear = (int) (grapeRatio*pear);
int grapeWorkerGrape = (int) (grapeRatio*grape);
int appleRemain = apple - appleWorkerApple - pearWorkerApple - grapeWorkerApple;
int pearRemain = pear - appleWorkerApple - pearWorkerApple - grapeWorkerApple;
int grapeRemain = grape - appleWorkerApple - pearWorkerApple - grapeWorkerApple;
Random r = new Random();
while(appleRemain > 0 && pearRemain > 0 && grapeRemain > 0) {
double target = r.nextDouble();
switch(r.nextInt(3)) {
case 0:
if(appleRemain > 0) {
appleRemain--
if(target < appleRatio)
appleWorkerApple++;
else if (target < appleRatio + grapeRatio)
pearWorkerApple++;
else
grapeWorkerApple++;
}
break;
case 1:
if(grapeRemain > 0)
// etc.
}
}
}
It's not particularly useful 'cause I've overused Numpy but I'll share since it's relevant
import numpy
import random
# apple, bannana, grapes, guava, melon, pear
fruits = numpy.array([100, 150, 175, 200, 230, 247])
# Bill, Bob, Dan, Fred, Joe
ratios = numpy.array([21, 7, 32, 13, 27])
# Original fruit amount for each worker: 0
worker_fruits = numpy.zeros((5, 6), dtype=int)
worker_lucky = numpy.zeros((5, 6), dtype=float)
# For each worker with his ratio
for worker, lucky, ratio in zip(worker_fruits, worker_lucky, ratios):
# Give him fruits, storing partials as weighting
to_give = (ratio * fruits) / 100
lucky += to_give % 1
worker += to_give
# Calculate how much we have left over
spares = fruits - worker_fruits.sum(axis=0)
# Share it out in a weighted distribution
for fruit, lucky, numspare in zip(worker_fruits.transpose(), worker_lucky.transpose(), spares):
if numspare:
indexes = numpy.arange(len(fruit))
add_to = numpy.random.choice(indexes, replace=False, size=numspare, p=lucky/numspare)
fruit[add_to] += 1
# Our results!
worker_fruits
#>>> array([[21, 31, 36, 42, 49, 51],
#>>> [ 7, 11, 12, 14, 16, 18],
#>>> [32, 48, 56, 64, 74, 79],
#>>> [13, 19, 23, 26, 29, 32],
#>>> [27, 41, 48, 54, 62, 67]])
# Proof it's perfectly shared
fruits - worker_fruits.sum(axis=0)
#>>> array([0, 0, 0, 0, 0, 0])
I wanted to write sieve of Eratosthenes which will work using specific number of threads. I figured out, that it will work in following way:
For 2 threads up to 17.
Thread-1 takes 2, and starts to remove multiple of 2 from List. Parallel Thread-2 takes 3 and does the same. After that Thread-1 takes 5( because there is no 4 in List) and Thread-2 takes 7 and so on until they reach end.
I wrote following piece of code:
private List<Integer> array = new ArrayList<Integer>();
private List<Integer> results = new ArrayList<Integer>();
public synchronized void run(){
while(array.size() > 0){
Integer tmp = array.get(0);
for(int i = 1; i < array.size(); i++){
if( (array.get(i).intValue() % tmp.intValue()) == 0)
array.remove(i);
}
results.add(array.get(0));
array.remove(0);
}
}
public void setArray(int x){
for(int i = 2; i < x; i++)
array.add(Integer.valueOf(i));
}
public void printArray(){
for(Integer i: results){
System.out.println(i);
}
}
This code works, but I added time measurement "tool" to my main class:
ThreadTask task = new ThreadTask();
task.setArray(5000);
Long beg = new Date().getTime();
for(int i = 0; i < 3;i++){
new Thread(task).start();
}
Long sleep = 1000L;
Thread.sleep(sleep);// I am sleeping main thread to wait until other Threads are done
task.printArray();
System.out.println("Time is "+(new Date().getTime()-beg-sleep));
The problem is that running this with 2 threads is slower than running with 1 thread, and 3 threads are slower than 2 threads. Could anyone explain me, why?
EDIT:
There is one important thing about that. I don't need it to be done as fast as it can be. I need it working on Threads for one reason. My Teacher wants to compare runtimes of running same program with 1, 2 .. n threads. Results should look like in this graph.
EDIT2:
I have rewritten code to following
private HashMap<Integer,Boolean> array = new HashMap<Integer,Boolean>();
private int counter = 1;
private int x;
public void run(){
while(counter < x-1){
do{
counter++;
}
while( array.get(counter));
int tmp = counter;
for(int i = tmp; i < array.size(); i+=tmp){
if( i!= tmp)
array.put(i,true);
}
try{
Thread.sleep(0L, 1);
}
catch (Exception e){}
}
}
public void setArray(int x){
this.x = x;
for(int i = 2; i < x; i++)
array.put(i, false);
}
public void printArray(){
for(int i = 2; i < array.size();i++){
if( !array.get(i))
System.out.println(i);
}
}
Now it uses HashMap and this is how it works:
Fill HashMap with keys from 2 to n and false values.
New thread goes into while loop which is based on counter variable. Counter represents current key.
Increment counter on the begging so new threads doesn't operate on counter of earlier started thread.
Put counter value into temporary variable tmp so we can work even when another thread increment counter
Iterate through the HashMap by incrementing i with tmp ( it is actually jumping on the multiplies of i) and set their values to true.
All keys which has true value are ignored in print method. Also counter skips them when incremented.
The problem is that it still works slower with more threads. What's wrong now?
The mistake is simpler than I first thought. All your threads are doing the same thing so each thread does more work. To make a multi-threaded program work faster you have to divide up the work, which has to be performed concurrently.
When you have one thread accessing a data structure, it can be in the fastest cache of one core, use multiple threads and they need to co-ordinate their actions and since most of the work is updating the data structure, a lot of time is lost as overhead. This is the case even though your data structure is not thread safe and is likely to have a corrupted result.
BTW updating an ArrayList is very expensive and using a collection objects is also an overhead.
You will get a much faster result using a BitSet and just one thread.
public class BitSetSieveMain {
private final BitSet set;
private final int size;
public BitSetSieveMain(int x) {
size = x + 1;
set = new BitSet(size);
set.flip(2, size);
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
long start = System.nanoTime();
BitSetSieveMain bitSetSieveMain = new BitSetSieveMain(5000);
bitSetSieveMain.sieve();
long time = System.nanoTime() - start;
System.out.println(time / 1000 + " micro-seconds to perform " + bitSetSieveMain);
}
}
public void sieve() {
int i = 2;
do {
for (int j = i*2; j < size; j += i)
set.clear(j);
i = set.nextSetBit(i+1);
} while (i > 0);
}
public String toString() {
return set.toString();
}
}
finally prints
87 micro-seconds to perform {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999}
public class apples {
private static String[] level1 = new String[] { "A", "B", "I", "K", "N", "O", "P", "S", "T", "W" };
public static void main(String[] args) {
int[] scores1 = { 99, 80, 56, 88, 70, 35, 67, 60, 78, 56 };
int[] correct1 = {20, 20, 13, 15, 22, 18, 19, 21, 23, 25};
int[] incorrect1 = {2, 1, 5, 2, 2, 5, 8, 1, 0, 0};
double[] percentage1 = new double[correct1.length];
for(int a = 0; a < correct1.length; a++ ){
percentage1[a] = (double)((correct1[a] / (correct1[a] + incorrect1[a]))*100);
}
System.out.println("Character \t Correct \t Incorrect \t Percentage");
for(int counter = 0; counter<scores1.length;counter++){
System.out.println(level1[counter] + "\t\t " + correct1[counter] + "\t\t " + incorrect1[counter] + "\t\t " + percentage1[counter]);
}
}
}
This outputs a table with 4 headings. The character, correct and incorrect columns show as expected. However the percentage row is not working properly. For example, character 'A', correct 20 and incorrect 2 gives a percentage of 0.0. Any 'incorrect' value > 0 outputs a percentage value of 0, and any 'incorrect' value which = 0 gives a percentage value of 100 (which is correct)... Can someone please explain where I have gone wrong?
You are dealing with integers here, and for integer division, the result is truncated. You'll need to cast the original values to double instead, or multiply one part by 1.0 to get it as a double:
percentage1[a] = ((correct1[a]*1.0 / (correct1[a] + incorrect1[a]))*100);
percentage1[a] = (double)((correct1[a] / (correct1[a] + incorrect1[a]))*100);
The above code casts to a double after the calculation is competed.
To cast as part of the calculation, use:
percentage1[a] = (( ((double)correct1[a]) / (correct1[a] + incorrect1[a]))*100);
You calculations here
percentage1[a] = (double)((correct1[a] / (correct1[a] + incorrect1[a]))*100);
perform integer division (you just cast them afterwards to double). If you want them to return the actual floating point division result, you have to cast all operands to double before the calculation.
So the fastest option would be to change this:
double[] correct1 = {20, 20, 13, 15, 22, 18, 19, 21, 23, 25};
double[] incorrect1 = {2, 1, 5, 2, 2, 5, 8, 1, 0, 0};
Another would be to change the computation to something like this
percentage1[a] = (1.0 * correct1[a] / (correct1[a] + incorrect1[a]))*100;
or to simplify a little:
percentage1[a] = 100.0 * correct1[a] / (correct1[a] + incorrect1[a]);