b******y 发帖数: 9224 | 1 jdk里面的源程序如下:
public int nextInt(int n) {
if (n<=0)
throw new IllegalArgumentException("n must be positive");
if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);
int bits, val;
do {
bits = next(31);
val = bits % n;
} while(bits - val + (n-1) < 0);
return val;
}
读不懂的地方是while(bits - val + (n-1) < 0);
为啥要这样判断呢? |
|
p*****2 发帖数: 21240 | 2 java 400多毫秒,scala 1000毫秒超时。
object test6 extends App {
def add(x:Int, y:Int):Unit={
if(x<1 || x>n || y<0) return;
val yy=Math.min(y,a(x)+1)
if(v(x)(yy)) return
queue+=Array(x,yy)
v(x)(yy)=true
}
val sc=new Scanner(new File("input.txt"))
val out=new PrintWriter("output.txt")
val n=sc.nextInt
val a=new Array[Int](n+1)
val v=Array.ofDim[Boolean](105, 100005)
val queue=Queue[Array[Int]]()
for(i<-1 to n) a(i)=sc.nextInt
... 阅读全帖 |
|
a******3 发帖数: 113 | 3 https://www.hackerrank.com/challenges/xor-key
public class Solution {
static void xor(int[] ar, int number, int left, int right){
int max=0;
for(int i=left;i<=right;i++){
int temp=number^ar[i];
if(temp>max)
max=temp;
}
System.out.println(max);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int test_case = in.nextInt();
for(int i=0;i
... 阅读全帖 |
|
a******3 发帖数: 113 | 4 https://www.hackerrank.com/challenges/xor-key
public class Solution {
static void xor(int[] ar, int number, int left, int right){
int max=0;
for(int i=left;i<=right;i++){
int temp=number^ar[i];
if(temp>max)
max=temp;
}
System.out.println(max);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int test_case = in.nextInt();
for(int i=0;i
... 阅读全帖 |
|
p*****2 发帖数: 21240 | 5
object test6 extends App {
val sc=new Scanner(System.in)
val n=sc.nextInt
val m=sc.nextInt
val mat=new Array[String](n)
val start=System.currentTimeMillis()
for(i<-0 until n) mat(i)=sc.next()
def check(i:Int, j:Int, k:Int, l:Int):Boolean={
val minX=math.min(i,k)
val maxX=math.max(i,k)
val minY=math.min(j,l)
val maxY=math.max(j,l)
var minR=true
var maxR=true
var minC=true
var maxC=true
... 阅读全帖 |
|
b***i 发帖数: 3043 | 6 GraphicsContext gc = canvas.getGraphicsContext2D();
以Brick为模板,在initTimeline()里面
KeyFrame kf = new KeyFrame(Config.ANIMATION_TIME, new EventHandler<
ActionEvent>() {
public void handle(ActionEvent event) {
加入
GraphicsContext gc = canvas.getGraphicsContext2D();
int x0=random.nextInt(Config.SCREEN_WIDTH);
int y0=random.nextInt(Config.SCREEN_HEIGHT);
int x1=random.nextInt(Config.SCREEN_WIDTH);
int y1=random.nextInt(Config.SCREEN_HEIGHT);
gc.setStroke(C... 阅读全帖 |
|
n****i 发帖数: 1024 | 7 主要是第一个comment那边,输入yes or no 然后取出第一个char赋值给tryAgain,我
用了tryAgain = scan.findInLine(".").charAt(0); 跑下来是出现一个框,根本就没
有赋值给tryAgain,求大神帮忙指点下,我哪里出错了。另外我用switch没问题吧
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors {
private static String[] choices = { "Rock", "Paper", "Scissors" };
public static void main (String[] args){
Scanner scan = new Scanner(System.in);
Random rGen = new Random();
String name;
int playerChoiceNum;
String playerC... 阅读全帖 |
|
d**e 发帖数: 6098 | 8 debug过,才知道java的Random.nextInt()可正可负的 -_-!
一直以为是非负的。
所以恰恰解释了为什么会多过m个.
用Random.nextInt(int)这个函数才产生非负。
所以改成 myr.nextInt(n)就可以了。 |
|
p*****2 发帖数: 21240 | 9
不是我要求高。还被抓出来另外一个bug
产生一个1-n的随机数
rand.nextInt()%n+1
主要是我对java不熟,搞不清楚可以nextInt(n)这么用,就用rand.nextInt()%n觉得也
没啥问题。结果也被抓了。 |
|
w***o 发帖数: 109 | 10 用这个Template就可以了:
import java.util.*;
class Solution{
static public void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
m = in.nextInt();
k = in.nextInt();
// your code
System.out.println(ret);
}
} |
|
c********l 发帖数: 8138 | 11 数组shuffle,经典的Fisher and Yates的算法是
public static void shuffle(List list, Random rnd) {
int size = list.size();
for (int i=size; i>1; i--)
swap(list, i-1, rnd.nextInt(i));
}
}
如果将
swap(list, i-1, rnd.nextInt(i));
改成
swap(list, i-1, rnd.nextInt(N));
会出错。
具体出错的原因是什么?怎么描述这种现象? |
|
w*******2 发帖数: 35 | 12 题目是这样的:You are required to use loops, decision making constructs and
static functions to write your program. Depreciation to a salvage value of 0
For tax purposes an item may be depreciated over a period of several years,
n. With the straight line method of depreciation, each year the item
depreciates by 1/nth of its original value. With the double-declining method
of depreciation, each year the item is depreciates by 2/nths of its value
at the beginning of the year. (in the last year it is depr... 阅读全帖 |
|
发帖数: 1 | 13 题目如下,可以直接google "hackrank stock maximize",测试自己代码是否正确:
https://www.hackerrank.com/challenges/stockmax
Your algorithms have become so good at predicting the market that you now
know what the share price of Wooden Orange Toothpicks Inc. (WOT) will be for
the next N days.
Each day, you can either buy one share of WOT, sell any number of shares of
WOT that you own, or not make any transaction at all. What is the maximum
profit you can obtain with an optimum trading strategy?
Input
The first line con... 阅读全帖 |
|
发帖数: 1 | 14 小白路过,学习了。
第一题是leetcode 271道.
public class Solution {
public String serialize(List strs) {
if (strs == null) return null;
StringBuffer ret = new StringBuffer();
for (String s : strs) ret.append(s.replace("#", "##")).append(" # ");
return ret.toString();
}
public List deserialize(String s) {
if (s == null) return null;
List ret = new ArrayList();
String[] array = s.split(" # ", -1);
for (int i = 0; ... 阅读全帖 |
|
c********l 发帖数: 8138 | 15 【 以下文字转载自 JobHunting 讨论区 】
发信人: coupondeal (Coupon Deal), 信区: JobHunting
标 题: 求问一道数组shuffle的问题
发信站: BBS 未名空间站 (Sun Mar 17 21:46:36 2013, 美东)
数组shuffle,经典的Fisher and Yates的算法是
public static void shuffle(List list, Random rnd) {
int size = list.size();
for (int i=size; i>1; i--)
swap(list, i-1, rnd.nextInt(i));
}
}
如果将
swap(list, i-1, rnd.nextInt(i));
改成
swap(list, i-1, rnd.nextInt(N));
会出错。
具体出错的原因是什么?怎么描述这种现象? |
|
l**********o 发帖数: 260 | 16 新手初到,写了几行,请大家指点
// this is to produce an integer array with one number duplicated
import java.util.*;
import java.io.*;
public class proAnArray{
public static void main(String[] args) throws IOException{
FileWriter fw = new FileWriter("Array.txt");
int N = 30000;
fw.write(N + "\n");
for(int i = 0; i < N; i++){
fw.write(i + " ");
if (i % 10 == 0) fw.write("\n");
}
int j = 400;
fw.write(j + "\n"); ... 阅读全帖 |
|
p*****2 发帖数: 21240 | 17
void dfs(int[] x, int[] y, int[] g, int start, int group)
{
if(g[start]>0)
return;
g[start]=group;
for(int i=0;i
if(x[i]==x[start] || y[i]==y[start])
dfs(x,y,g,i,group);
}
int[] x=new int[n];
int[] y=new int[n];
for(int i=0;i
{
x[i]=in.nextInt();
y[i]=in.nextInt();
}
int[] g=new int[n];
int group=0;
... 阅读全帖 |
|
s********x 发帖数: 914 | 18 切磋一下. running time 应该是 less than log(K)
public class RandomNextIntExceptK {
private int[] kk;
private int[] kAdd;
private Random rand = new Random();
public RandomNextIntExceptK(int[] k) {
Map kCount = new TreeMap();
for (int i = 0; i < k.length; i++)
{
int key = k[i] - i;
if (kCount.containsKey(key))
{
int count = kCount.get(key);
kCount.put(key, cou... 阅读全帖 |
|
z******w 发帖数: 36 | 19 //用dp做的一个O(n^3)的解
import java.util.Scanner;
public class StreetTraversal {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] dis = new int[n][n];
for (int i = 0; i < n; i ++) {
dis[i] = new int[n];
for (int j = 0; j < n; j ++) {
dis[i][j] = sc.nextInt();
}
}
int[][] dp = new int[n+1][n+1];
for (int i = 1; i <= n; i ++)
... 阅读全帖 |
|
s**********e 发帖数: 326 | 20 来自主题: JobHunting版 - 一个小题目 贴个我的代码:
evenProb have 50/50 probability to return true, genAnyProb can return true
with any prob(first parameter)
main should call genAnyProb like this: genAnyProb(0.6,1,0.00001)
public boolean evenProb() {
return new Random().nextInt(2) == 0;
}
public boolean genAnyProb(double prob, double base, double epsilon) {
if (prob * base < epsilon) {
return true;
}
if (prob == 0.5) {
return evenProb();
} else if (prob > 0.5) {
... 阅读全帖 |
|
e********3 发帖数: 18578 | 21 BFS+DP,而且需要maintain两个距离,一个是到终点的最小距离,一个是到起点的最小
距离,计算终点的距离需要backtrack,到起点的简单比较保存最小值就行了,类似
Dijkstra算法。电面就考这个有点偏难了,尤其还是同胞就操蛋了,要是老中这么考老
印我绝对赞成。简单的实现还可以把障碍物那个的距离设成100啥的,这样自然就知道
要绕过了。
这个题目的难度比reverse linkedlist, atoi难了几个数量级。。。
我贴两个我自己写的代码抛砖引玉一下,第一个是Harry Potter最小的strength通关,
第二个是经典的Dijkstra algorithm,都是附带了测试数据自动生成的方法,你把这两
个组合一下基本就能解这道题了,过两天我有空了来写一下这道题的具体实现。
import java.util.*;
public class HarryPotter{
private static Random rand = new Random();
private static int[][] matrix;
private static ... 阅读全帖 |
|
l*****n 发帖数: 246 | 22 没什么思路,想这样做,不知道会不会被人鄙视:
public int[][] generateRandomBoard(int NColors, int N, int M) {
int[][] board = new int[N][M];
boolean isEnd = false;
while(!isEnd){
generateRandomBoard(board, NColors);
isEnd = checkBoard(board);
}
return board;
}
private void generateRandomBoard(int[][] board, int NColors) {
Random rm = new Random();
int N = board.length;
int M = board[0].length;
for(int i=0; i
for(int j=0; j
int te... 阅读全帖 |
|
l***i 发帖数: 168 | 23 写一个小程序。前面引用了交互界面,import java.util.*;
用户输入年份,然后检查是否在要求的区间内,1600 - 2400, 如果不是,给出提示
,并要求重新输入。我写了下面的code,可是compile的时候,认为最后的那个不对。
删掉最后一行就可能死循环。我不知道该如何处理。请帮忙。
System.out.print("What is the year? ");
int ranran_Year = input.nextInt();
while (ranran_Year < 1600 || ranran_Year > 2400) {
System.out.println("Invalid date with wrong year.");
System.out.print("Input a number between 1600 and 2400, inclusive: ");
int ranran_Year = input.nextInt(); //此处如何处理??
} |
|
A**u 发帖数: 2458 | 24 import java.util.*;
import java.util.concurrent.locks.*;
public class PC_unsyn
{
public static void main(String[] args)
{
IntBuffer b = new IntBuffer();
Producer p = new Producer(b);
Consumer c = new Consumer(b);
p.setName("Producer");
c.setName("Consumer");
p.start();
c.start();
}
}
class IntBuffer
{
private int index;
private int[] buffer = new int[8];
private Lock bufferLock = new ReentrantLock();
private Cond... 阅读全帖 |
|
Q*****l 发帖数: 26 | 25 判断a是0-99的整数
a = scan.nextInt();
while ((a<0)|(a>99)|判断a非integer)
{
显示报错
a = scan.nextInt();
}
如何在不引入对象做新的method的情况下,只用一种函数判断a非integer。
我知道还可以用if语句,请问能有什么最简单的函数判断a非integer吗?
比如 函数(a) == false.
用什么函数?
多谢 |
|
n**d 发帖数: 112 | 26 也找了一个用hash实现计数功能的 但是就是不知道怎么和在一起。。麻烦各位大师帮
帮忙
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Map;
import java.util.Scanner;
public class SortUniqueInt
{
public static void main(String[] args)
{
Map result = new HashMap();
Scanner input = new Scanner(System.in);
try
{
int n = input.nextInt();
while(n>0)
{
int number = input.nextInt( |
|
A**u 发帖数: 2458 | 27 【 以下文字转载自 Java 讨论区 】
发信人: Augu (奥古), 信区: Java
标 题: 求教一个Java问题 IllegalMonitorStateException
发信站: BBS 未名空间站 (Tue Dec 11 11:31:48 2012, 美东)
import java.util.*;
import java.util.concurrent.locks.*;
public class PC_unsyn
{
public static void main(String[] args)
{
IntBuffer b = new IntBuffer();
Producer p = new Producer(b);
Consumer c = new Consumer(b);
p.setName("Producer");
c.setName("Consumer");
p.start();
c.start();
}
}
class Int... 阅读全帖 |
|
s****b 发帖数: 2039 | 28 你不是问有没有什么好办法吗?跑下面这个程序就可以了,和是1,每个随机数乘0.
001。我
跑了半天还没得到结果。你自己用快的计算机去跑吧。
***
import java.util.Random;
public class Haha {
public static void main(String[] args) {
Random rn = new Random();
int t=0;
String s="";
while (t != 1000) {
t=0;
s="";
for (int i=0; i<10; i++) {
int r = rn.nextInt(1001);
t=t+r;
s=s+r+" ";
}
}
System.out.println("sum = "+t);
... 阅读全帖 |
|
s****b 发帖数: 2039 | 29 用下面这个办法,可以看到每次的10个随机数,以及和是多少。最后到和是1000
停止。
***
import java.util.Random;
public class Ha {
public static void main(String[] args) {
Random rn = new Random();
int t=0;
String s="";
while (t != 1000) {
t=0;
s="";
for (int i=0; i<10; i++) {
int r = rn.nextInt(1001);
t=t+r;
s=s+r+" ";
System.out.println("sum = "+t);
System.out.println("the random numb... 阅读全帖 |
|
s*****i 发帖数: 355 | 30 对任意给定概率p (p<0.5),找到2p的irreducible fraction. 找即约分数可以一个
while循环每次乘以10再mod 1,直到余数为零为止。然后找分子分母的最小公倍数
let w=2p=A/B, then
Random r = new Random();
toss = Math.random();
if ( (r.nextInt(B) % B < A) && (toss < 0.5) )
return true;
else
return false;
|
|
r****o 发帖数: 1950 | 31 请问这个r.nextInt(B)是什么意思
原题中的随机函数只能返回0或1吧。 |
|
s*****i 发帖数: 355 | 32 你这样应该是对的,如果只给了一个函数,随机返回0或1的话。
我的代码里面用了java api函数, nextInt(B)是随机返回 [0, B) 之间任意整数。 |
|
c*****h 发帖数: 166 | 33 这题的trick在哪?我感觉就是把数组shuffle一下就好了吧
for (int i=size; i>1; i--)
swap(array, i-1, rnd.nextInt(i)); |
|
I**A 发帖数: 2345 | 34 我用Java写的
public static void genKnuth(int m, int n)
{
Random myr = new Random();
for(int i=0; i
if((myr.nextInt() % (n-i)) < m){
System.out.print(i + " ");
m--;
}
}
public static void main(String[] args) {
genKnuth(5,20);
}
产生的总是多于5个。。
难道这个random function有问题???我觉得不应该啊。
而且我把你的解释和作者的解释又看了好几遍,还是没明白。。 |
|
s******5 发帖数: 673 | 35 Can you use LinkedList?
Insertion and Deletion are O(1).
For getRandom(), i am not sure how much time Random().nextInt() cost...
For hashtable, the insertion could be more than O(1) if there are collisions
. |
|
s******e 发帖数: 108 | 36 public class RandomHash {
HashMap hashmap = new HashMap();
Vector vec = new Vector();
public void insert(K key) {
vec.add(key);
hashmap.put(key, new Integer(vec.size()-1));
}
public K getRand() {
if(vec.size()<=0)
return null;
Random randomGenerator = new Random();
int rndnum = randomGenerator.nextInt(vec.size());
return vec.get(rndnum);
}
public boole... 阅读全帖 |
|
s******e 发帖数: 108 | 37 可以用 hashset 来替代 vector ,
public class RandomHash {
HashMap > hashmap = new HashMap
LinkedHashSet>();
Vector vec = new Vector();
public void insert(K key) {
vec.add(key);
if( ! hashmap.containsKey(key) ) {
LinkedHashSet hashSet = new
LinkedHashSet();
hashSet.add(new Integer(vec.size()-1));
hashmap.put(key,hashSet);
} else {
h... 阅读全帖 |
|
y***y 发帖数: 224 | 38 void randint(){
Random r = new Random();
int temp=0;
int index=0;
int[] a = new int[52];
for(int i=0;i
a[i]=i;
for(int i=0;i
index=r.nextInt(52-i)+i;
temp=a[i];
a[i]=a[index];
a[index]=temp;
}
for(int i=0;i
System.out.print(a[i]+" ");
} |
|
h**********d 发帖数: 4313 | 39 明白了,谢谢
我找到了一个类似题目的解法,是一个file里选10行
public void reservoirSampling () throws FileNotFoundException,
IOException {
File f = new File("data.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
String currentLine;
int reservoirSize=10;
List reservoirList= new ArrayList(reservoirSize);
int count=0;
Random ra = new Random();
int randomNumber;
while ((currentLine = br.readLine()) != null){
count ++;
if (count<=10){
reservoirList.add(cu... 阅读全帖 |
|
g***s 发帖数: 3811 | 40 public class ColorBalls {
public static void arrange(int[] balls, int colorNum){
int[] count = new int[colorNum];
int[] pointers = new int[colorNum];
//count color
for (int color : balls) count[color]++;
//set the pointers
for (int i=0;i
pointers[i+1] += pointers[i] + count[i];
}
int currentColor = 0;
int c = count[currentColor];
for (int pos=0;pos
if (... 阅读全帖 |
|
p*****2 发帖数: 21240 | 41
是。因为做过很多类似的DP题,上来就往DP那里想了。做的时候才发觉DP帮助不明显。
但是测试用例也都过了,就提交了。这题证明greedy可以也得花一些时间。不是很直观
。如果只是有思路的话,还是会在greedy和dp只见纠缠。感觉比赛的时候很难掌握呀。
另外,上一下greedy的代码。
public class test2 {
static String s;
static int k;
static HashSet pairs = new HashSet();
static boolean isForbidden(char[] arr) {
Arrays.sort(arr);
return pairs.contains(new String(arr));
}
static int Play(String str) {
int count = 0;
int count1 = 0;
int count2 = 0;
int j = 0;
for (int... 阅读全帖 |
|
p*****2 发帖数: 21240 | 42
那我上code了。
public class test
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int x=Math.abs(in.nextInt());
int step=1;
int start=0;
while(start
start+=step++;
while((start-x)%2!=0)
start+=step++;
System.out.println(step-1);
}
} |
|
f******h 发帖数: 45 | 43 第二题用java 这样子写行么?
public class ReserviorSampling {
public ListNode sampling(ListNode head){
ListNode s = head;
Random rand = new Random();
int count = 1;
while(head != null){
int position = (int) (rand.nextInt(count) + 1);
count++;
if(position == 1)
s = head;
}
return s;
}
}
这题怎么测试啊? 要生成很长的linkedlist 然后随机选择,看概率是否接近1/n? |
|
f******h 发帖数: 45 | 44 第二题用java 这样子写行么?
public class ReserviorSampling {
public ListNode sampling(ListNode head){
ListNode s = head;
Random rand = new Random();
int count = 1;
while(head != null){
int position = (int) (rand.nextInt(count) + 1);
count++;
if(position == 1)
s = head;
}
return s;
}
}
这题怎么测试啊? 要生成很长的linkedlist 然后随机选择,看概率是否接近1/n? |
|
p*****2 发帖数: 21240 | 45
TreeNode ans=null;
int count=0;
Random rand=new Random();
void getRandNode(TreeNode root)
{
if(root==null) return;
count++;
if(rand.nextInt(count)==0)
ans=root;
getRandNode(root.left);
getRandNode(root.right);
} |
|
d*********g 发帖数: 154 | 46 练习一个
class RandomNodeGetterInBinaryTree
{
private static int totalNumNodesSoFar = 0;
private static TreeNode result = new TreeNode();
public TreeNode GetRandomNodeInBinaryTree(TreeNode root)
{
PreOrderTraverse(root);
return result;
}
private void PreOrderTraverse(TreeNode node)
{
if(node == null) return;
ReservoirSampling(node);
PreOrderTraverse(node.left);
PreOrderTraverse(node.right);
}
priv... 阅读全帖 |
|
m*****k 发帖数: 731 | 47 如果你都可以生成num = 1<
那干嘛不直接 new Random().nextInt(n) 来产生一个 int x, where n-1>=x>=0,
return x==0 就完了。
我实在是看不出(double)num*rand() 为何能work?
-1 |
|
s****0 发帖数: 117 | 48 package myutil;
import java.util.Scanner;
import java.util.Stack;
public class ParseExp {
Stack oprand = new Stack();
Stack oprator = new Stack();
static int[] code = new int[256];
static {
code['+'] = 10;
code['-'] = 11;
code['*'] = 20;
code['/'] = 21;
code['^'] = 30;
code['$'] = 0;
code['('] = 100;
code[')'] = 1;
}
public ParseExp() {
}
public Integer parse(String... 阅读全帖 |
|
s****0 发帖数: 117 | 49 package myutil;
import java.util.Scanner;
import java.util.Stack;
public class ParseExp {
Stack oprand = new Stack();
Stack oprator = new Stack();
static int[] code = new int[256];
static {
code['+'] = 10;
code['-'] = 11;
code['*'] = 20;
code['/'] = 21;
code['^'] = 30;
code['$'] = 0;
code['('] = 100;
code[')'] = 1;
}
public ParseExp() {
}
public Integer parse(String... 阅读全帖 |
|
a******3 发帖数: 113 | 50 https://www.hackerrank.com/challenges/walking-on-grids
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static int count(int n){
int[][] ar=new int[n][n];
ar[0][0]=1;
for(int i=0;i
for(int j=0;j<=i;j++){
if(i==0 && j==0)
continue;
int left=0, up=0;
if(i-1>=0 && i!=j)
up=ar[i-1... 阅读全帖 |
|