I'm trying to generate ONE number, but every time I do this it prints out thousands of numbers.
Here is my code:
Random r = new Random();
int number;
int number2;
for(int i = 0; i != 1; i++) {
number = r.nextInt(6);
number2 = r.nextInt(6);
Font fnt = new Font("arial", 1, 200);
g.setColor(Color.white);
g.setFont(fnt);
g.drawString(number + number2 + "", Program.WIDTH/2-100, 300);
}
Try this.
Random r = new Random();
int number;
int number2;
for(int i = 0; i < 1; i++) {
number = r.nextInt(6);
number2 = r.nextInt(6);
Font fnt = new Font("arial", 1, 200);
g.setColor(Color.white);
g.setFont(fnt);
g.drawString(number + number2 + "", Program.WIDTH/2-100, 300);
}
According to your code it looks like your are trying to run the loop once. If this is the case, remove the FOR loop. If this code is in a function that runs on a screen refresh, it will generate thousands of random numbers.
I think that making functions give you more flexibility later :)
For example :
public static int myRandom(int min, int max) {
if(max >= min) {
Random r = new Random();
return r.nextInt((max - min) + 1) + min;
}
}
Related
I have a task, it can be done in VB.net language or other programming languages as well. i'm just looking for an idea how it can be done
Task description:
Bank transfer comes to me, let's say on 10 000. Now I have to find the combination of invoices that can be covered by this amount - and the total amount (10 000) will be fully allocated.
No Invoice| Value
Invoice 1 | 3000
Invoice 2 | 1400
Invoice 3 | 9100
Invoice 4 | 1000
Invoice 5 | 8500
Invoice 6 | 900
For example, based on this case I would like to pay for Invoice 3 (9100) + Invoice 6 (900) = 10 000
I was trying to adjust this problem to knapsack algorithm or partition sort, but in my opinion it is too complex
Honestly this is very much like Knapsack. The difference is that here the weight of the item is equal its value. So just a particular case of Knapsack. I went on geeksforgeeks and modified their algorithm a bit, here it is in c#:
using System ;
class GFG {
// A utility function that returns
// maximum of two integers
static int max(int a, int b)
{
return (a > b) ? a : b;
}
// Prints the items which are put
// in a knapsack of capacity W
static void printknapSack(int W, int []wt,
int []val, int n)
{
int i, w;
int [,]K = new int[n + 1,W + 1];
// Build table K[][] in bottom up manner
for (i = 0; i <= n; i++) {
for (w = 0; w <= W; w++) {
if (i == 0 || w == 0)
K[i,w] = 0;
else if (wt[i - 1] <= w)
K[i,w] = Math.Max(val[i - 1] +
K[i - 1,w - wt[i - 1]], K[i - 1,w]);
else
K[i,w] = K[i - 1,w];
}
}
// stores the result of Knapsack
int res = K[n,W];
Console.WriteLine(res);
w = W;
for (i = n; i > 0 && res > 0; i--) {
// either the result comes from the top
// (K[i-1][w]) or from (val[i-1] + K[i-1]
// [w-wt[i-1]]) as in Knapsack table. If
// it comes from the latter one/ it means
// the item is included.
if (res == K[i - 1,w])
continue;
else {
// This item is included.
Console.Write(wt[i - 1] + " ");
// Since this weight is included its
// value is deducted
res = res - val[i - 1];
w = w - wt[i - 1];
}
}
}
// Driver code
public static void Main()
{
int []val = { 3000, 1400, 9100, 1000, 8500, 900 };
int []wt = { 3000, 1400, 9100, 1000, 8500, 900 };
int W = 10000;
int n = val.Length;
printknapSack(W, wt, val, n);
}
}
Running this code will give the output:
10000
900 9100
More details and explanations for the general problem https://www.geeksforgeeks.org/printing-items-01-knapsack/
I have an example with recursive function in c#.
static void Main(string[] args)
{
List<int> invoices = new List<int> { 3000, 1400, 9100, 1000, 8500, 900};
int totalAmount = 10000;
List<int> rest = new List<int>();
sum(invoices, totalAmount, rest);
Console.ReadLine();
}
private static void sum(List<int> invoices, int totalAmount, List<int> rest)
{
int currentSum = rest.Sum();
if (currentSum == totalAmount)
{
Console.WriteLine("Sum: " + totalAmount + " is reached with following values.");
foreach (var restVal in rest)
Console.WriteLine(restVal + ",");
}
if (currentSum >= totalAmount)
return;
for(int i=0; i<invoices.Count; i++)
{
int inv = invoices[i];
List<int> firstPart = new List<int>();
List<int> secondPart = new List<int>();
firstPart.Add(invoices[i]);
for (int j = i + 1; j < invoices.Count; j++)
secondPart.Add(invoices[j]);
firstPart = rest.Concat(firstPart).ToList();
sum(secondPart, totalAmount, firstPart);
}
}
I think this is also close to knapsack algorithm and will be very costly for large dataset.
I learnt about pascal's triangle and achieved to print one in Java with O(n2) complexity.
Now for the next part I have to find the sequences of numbers that form a hockey stick pattern and I am stuck here. Any help will be great!
Also this link will help you understand what a hockey stick pattern is in pascal's triangle.
Below is the code I wrote to return the triangle
int[][] printPascal(int n)
{
int[][] arr= new int[n][n];
for(int line=0;line<n;line++)
{
for(int i=0;i<=line;i++)
{
if(line==i|| i==0)
{
arr[line][i]=1;
}
else
{
arr[line][i]=arr[line-1][i-1]+arr[line-1][i];
}
System.out.print(arr[line][i]+" ");
}
System.out.println();
}
return arr;
}
I tried to do something but I am getting arrayIndexOutOfBound
void printSequence(int[][]arr)
{
int n= arr.length;
Map<Integer, List<Integer>> map =new HashMap<>();
List<Integer> sequence= new ArrayList<>();
for(int i=0;i<=n;i++)
{
int count=0;
int res=0;
for(int line=0;line<n;line++)
{
sequence.add(arr[line][i]);
res=sumList(sequence);
if(res!=arr[line+1][i+1])
{
sequence=new ArrayList<>();
continue;
}
else
{
List<Integer> resSeq= new ArrayList<>(sequence);
resSeq.add(arr[line+1][i+1]);
map.put(++count, resSeq);
res=0;
}
}
}
}
I need to find all the sequences that satisfies the rule
nCr+(n+1)Cr+(n+2)Cr+.....+(n+k)Cr=(n+k+1)Cr
And these sequences if marked on a Pascal's triangle will resemble a hockey stick.
Here is how my solution looks like
void hockeyNumbers(int[][] arr) {
int n = arr.length;
List<Integer> sequence;
Map<Integer, List<Integer>> map = new HashMap<>();
int count = 0;
for (int i = 0; i < n; i++) {
int res = 0;
sequence = new ArrayList<>();
for (int line = i; line < n - 1; line++) {
sequence.add(arr[line][i]);
res = sumList(sequence);
if (res == arr[line + 1][i + 1]) {
List<Integer> resSeq = new ArrayList<>(sequence);
resSeq.add(arr[line + 1][i + 1]);
if (resSeq.size() > 2) {
map.put(++count, resSeq);
}
res = 0;
}
}
}
}
I have worked the solution and it looks like below. I am storing all the sequences in a hashmap for later use.
void hockeyNumbers(int[][] arr) {
int n = arr.length;
List<Integer> sequence;
Map<Integer, List<Integer>> map = new HashMap<>();
int count = 0;
for (int i = 0; i < n; i++) {
int res = 0;
sequence = new ArrayList<>();
for (int line = i; line < n - 1; line++) {
sequence.add(arr[line][i]);
res = sumList(sequence);
if (res == arr[line + 1][i + 1]) {
List<Integer> resSeq = new ArrayList<>(sequence);
resSeq.add(arr[line + 1][i + 1]);
if (resSeq.size() > 2) {
map.put(++count, resSeq);
}
res = 0;
}
}
}
}
I have tried finding the hockey stick through Pascal's triangle with some boundary conditions.(0 < n <= 30000 && 0 < l <= 100) where n is the row number(rows starts with 0) and l is the length of the hockey stick(length starts with 0).But, these extreme conditions create timeout issues.
Now, one way to create Pascal's triangle is using Binomial coefficients.
Following the same thing, we can get the hockey stick. For this, we don't need to create the complete triangle. You just need the row number and the length of the hockey stick.
We know that hockey stick always starts with 1 and second index of that row will be the row number itself.
So now, we already have two values of the hockey stick 1 and (Row+1).
The next value can be generated through Binomial coefficients using the following :
C(line, i) = C(line, i-1) * (line - i + 1) / i
private static void hockeyStick(int row, int length) {
System.out.println("Hockey stick statring from " + row);
List<Integer> finalResult = new ArrayList<>(Arrays.asList(1, ++row));
int oldValue = 1;
int newValue = row;
int sum = row + 1;
for (int i = 2; i < length - 1; i++) {
finalResult.add(newValuebimialCoefficient(oldValue + newValue, i, ++row));
oldValue += newValue;
newValue = finalResult.get(i);
sum += newValue;
}
finalResult.add(sum);
System.out.println(finalResult);
}
private static int newValuebimialCoefficient(int oldValue, int index, int line) {
return (oldValue * (line - index + 1) / index);
}
I think this should be helpful.
I'm a beginner coder and I came up with an algorithm for sorting (DexSort) that typically works much faster than a standard Quicksort. This is assuming the number of ALL POSSIBLE values in a set/array is less than N^2, where N is the number of items I am trying to sort. I'm trying to find a way to optimize it so it doesn't necessarily have to depend on ALL POSSIBLE VALUES and just a subset of values that are relevant.
For example....say I have an array of random numbers where array.length = 10 million. My algorithm is only faster than Quicksort (on average) when the total number of all possible values is less than N^2 (i.e. 10^7 * 10^7 = 10 ^ 14). Now, say there are 10^14 actual values that can be found in an array. In this instant, my algorithm will run at roughly O(10^14). Can anyone think of a way to where I could reduce this?
Here is my code in Java:
package sort;
import java.util.*;
public class DexSort {
public static Comparable[] dexSort(Comparable[] c, int max){
//The variable int max is the maximum number of possible values
//E.g. If you are trying to sort 7-digit phone numbers, max = Math.pow(10,8) - 1, or 10^8 - 1
int size = c.length;
Comparable[] sorted = new Comparable[size];
int[] array = new int[max+1];
for (int i = 0; i < size; i++){
int val = (int) c[i];
int count = array[val];
count++;
array[val] = count;
}
int next = 0;
while (next < size){
for (int i = 0; i <= max; i++){
int count = array[i];
if (count > 0){
for (int j = 0; j < count; j++){
sorted[next] = i;
next++;
}
}
}
}
return sorted;
}
public static void main(String[] args){
Random r = new Random(7);
for (double n = 4; n < 8; n++){
double size = Math.pow(10, n);
System.out.println("---------------------------------------------");
System.out.println("Filling array size: 10^" + n);
System.out.println("---------------------------------------------\n");
Comparable[] array = fillArray((int)size, r); //Create array of random numbers of specified size
System.out.println("Array filled"); //Tests different array sizes by incrementing a power of 10
System.out.println("---------------------------------------------\n");
double max = size; //Arbitrarily set the maximum value possible as the array size
//Runtime will depend heavily on max if max>>>> size (See dexSort method)
//Overall, runtime will be O(max) when max >>>>> size
double t0 = System.nanoTime();
array = dexSort(array, (int) max);
double tF = System.nanoTime();
double nanoSecs = tF - t0;
double secs = nanoSecs/Math.pow(10, 9);
System.out.println("DEX sort complete");
System.out.println("It took " + String.format("%.3f", secs) + " seconds to sort an array of size 10^" + n);
//printArray(array); //Uncomment this line to print sorted array to console
System.out.println();
System.out.println("---------------------------------------------");
System.out.println("---------------------------------------------\n\n");
}
}
public static Comparable[] fillArray(int size, Random r){
Comparable[] c = new Comparable[size];
for (int i = 0; i < size; i++){
/*if ((i+1)%10000000 == 0){
System.out.println(((i+1)/1000000) + " million filled");
}*/
c[i] = r.nextInt(size)+1;
}
return c;
}
public static void printArray(Comparable[] c){
for (int i = 0; i < c.length; i++){
if (i%10 == 0){
System.out.println();
}
System.out.print(c[i] + "\t");
}
}
}
Hi Here is a Q that was asked in Adobe Interview.
Numbers ending in 3 have at least one multiple having all ones. for
eg., 3 and 13 have amultiples like 111 and 111111 respectively. Given
such a no. , find the smallest such multiple of that number. The
multiple can exceed the range of int, long. You cannot use any
complex data structure.
Can you provide me with an efficient solution
got the answer now :)
int count=1, rem=1;
while(rem)
{
rem= (rem*10+1)%n; count++;
}
while(count--){ cout<<"1";}
Here is an attempt to do it more efficiently that trying 1, 11, 111, 111.. Could this pay off. Is there a more elegant answer better than trying numbers one at a time?
Write the numbers 1, 11, 111, ... as (10^k - 1) / 9, where the division is known to be exact. Given a target number in the form 10x+3 we want to find the smallest k solving (10^k - 1) / 9 = Y(10x + 3) where Y is an integer. Look for small solutions of 10^k = 1 mod 9(10x + 3). This is http://en.wikipedia.org/wiki/Discrete_logarithm except that arithmetic mod 9(10x + 3) does not necessarily form a group - however the http://en.wikipedia.org/wiki/Baby-step_giant-step algorithm should still apply and could be used to search steadily increasing ranges of k, instead of searching possible values of k one at a time.
#include <iostream>
using namespace std;
int main() {
int t;
cin>>t;
while(t--){
long long n;
cin>>n;
long long cur = 1;
while(cur%n!=0){
cur = cur*10+1;
}
cout<<cur<<endl;
}
return 0;
}
Solution independent of output size:
public String ones(int n)
{
int i, m = 1;
String num="1";
for (i = 1; i <= n; i++) {
if (m == 0)
return num;
/* Solution found */
num=num+"1";
m = (10*m + 1) % n;
}
return null; /* No solution */
}
If you are looking for a Solution in Java, here it is
public static void main(String[] args) {
int input = 13; // this can be any number ending with 3
int minAllOnesNum = 1;
int nextAllOnesNum= minAllOnesNum;
int numberof1s=1;
int count = 0;
while(true)
{
count++;
if(nextAllOnesNum%input == 0 )
{
break;
}
nextAllOnesNum = nextAllOnesNum*10 + 1;
if(nextAllOnesNum>=input) {
nextAllOnesNum%=input;
}
numberof1s++;
}
System.out.println("Number of iterations : " + count);
for(int i=1; i<=numberof1s; i++) {
System.out.print("1");
}
}
If you are looking for a Solution in Java, here it is
public static void main(String[] args) {
int input = 55333;
int minAllOnesNum = 1;
int nextAllOnesNum= minAllOnesNum;
int numberof1s=1;
int count = 0;
while(true)
{
count++;
if(nextAllOnesNum%input == 0 )
{
break;
}
nextAllOnesNum = nextAllOnesNum*10 + 1;
if(nextAllOnesNum>=input) {
nextAllOnesNum%=input;
}
numberof1s++;
}
System.out.println("Number of Iterations: " + count);
for(int i=1; i<=numberof1s; i++) {
System.out.print("1");
}
}
static int findOnes(int num){
int i = 1 ;
int power = 0;
while (i % num != 0){
i = (i * (10^power)) + 1;
}
return i;
}
I'm a design teacher trying to help a student with a programming challenge, so I code for fun, but I'm no expert.
She needs to find the mode (most frequent value) in a dataset built using data from sensors coupled to an Arduino, and then activate some functions based on the result.
We've got most of it figured out, except how to calculate the mode in Arduino. I found the post Get the element with the highest occurrence in an array that solves the problem in JavaScript, but I haven't been able to "port" it.
I've used a HashMap to replace the js {} dynamic object instance and floats, but #weberik's port looks more straightforward.
void setup() {
int numValues = 10;
float[] values = new float[numValues]; //Create an empty sample array
for(int i = 0 ; i < numValues ; i++) values[i] = random(0.0,100.0); //Populate it with random values.
println("mode: " + mode(values));
}
float mode(float[] source) {
if (source.length == 0)
return -1;
HashMap<Float,Integer> modeMap = new HashMap<Float,Integer>();
float result = source[0];
int maxCount = 1;
for (int i = 0; i < source.length; i++) {
float el = source[i];
if (modeMap.get(el) == null)
modeMap.put(el,1);
else
modeMap.put(el,modeMap.get(el)+1);
if (modeMap.get(el) > maxCount) {
result = el;
maxCount = modeMap.get(el);
}
}
return result;
}
You've mentioned sensor input, so I presume data will be sampled continuously, so values could be stored at a certain interval, then sent to Processing for the mode.
Just a wild guess, but isn't she looking to average/smooth out sensor readings a bit?
If so, she could cache a few values (say 10) in an array in Arduino and get the average everytime a new values is added:
int vals[10]; //Array to store caches values.
void setup() {
Serial.begin(9600);
for (int i=0 ; i < 10 ; i++)
vals[i] = 0; //Init with zeroes
}
void loop() {
delay(100);
int currentVal = average(analogRead(0));
//Serial.print(currentVal,BYTE);
Serial.println(currentVal);
}
int average(int newVal) {
int total = 0; //Used to store the addition of all currently cached values
for(int i = 9; i > 0; i--) { //Loop backwards from the one before last to 0
vals[i] = vals[i-1]; //Overwrite the prev. value with the current(shift values in array by 1)
total += vals[i]; //Add to total
}
vals[0] = newVal; //Add the newest value at the start of the array
total += vals[0]; //Add that to the total as well
return total *= .1; //Get the average (for 10 elemnts) same as total /= 10, but multiplication is faster than division.
}
I ported the code from your linked post to Processing, but it's limited to int arrays.
I hope that helps.
void setup()
{
int[] numbers = {1, 2, 3, 2, 1, 1, 1, 3, 4, 5, 2};
println(mode(numbers));
}
int mode(int[] array) {
int[] modeMap = new int [array.length];
int maxEl = array[0];
int maxCount = 1;
for (int i = 0; i < array.length; i++) {
int el = array[i];
if (modeMap[el] == 0) {
modeMap[el] = 1;
}
else {
modeMap[el]++;
}
if (modeMap[el] > maxCount) {
maxEl = el;
maxCount = modeMap[el];
}
}
return maxEl;
}