Skip to content

Instantly share code, notes, and snippets.

@SheepTester
Created January 26, 2019 05:57
Show Gist options
  • Select an option

  • Save SheepTester/ba1107804c1cce9fb7bb1825e39a55a7 to your computer and use it in GitHub Desktop.

Select an option

Save SheepTester/ba1107804c1cce9fb7bb1825e39a55a7 to your computer and use it in GitHub Desktop.
Randp generates a random number between 1 and n, and will never generate that again; no loops or recursion! - http://paleyontology.com/AP_CS/randp.html
public class Randp {
private int[] nums;
private int numsLeft;
public Randp(int n) {
nums = new int[n];
numsLeft = n;
}
public int nextInt() {
if (numsLeft <= 0) return 0;
int index = (int) (Math.random() * numsLeft);
int num = nums[index];
numsLeft--;
if (nums[numsLeft] == 0) nums[index] = numsLeft + 1;
else nums[index] = nums[numsLeft];
if (num == 0) return index + 1;
else return num;
}
public static void main(String[] args) {
Randp r = new Randp(6);
// 1-6
System.out.println(r.nextInt());
System.out.println(r.nextInt());
System.out.println(r.nextInt());
System.out.println(r.nextInt());
System.out.println(r.nextInt());
System.out.println(r.nextInt());
// 0
System.out.println(r.nextInt());
System.out.println(r.nextInt());
}
}
class Randp {
constructor(n) {
this.nums = [];
this.numsLeft = n;
}
nextInt() {
if (this.numsLeft <= 0) return 0;
const index = Math.floor(Math.random() * this.numsLeft);
const num = this.nums[index];
this.numsLeft--;
if (this.nums[this.numsLeft])
this.nums[index] = this.nums[this.numsLeft];
else
this.nums[index] = this.numsLeft + 1;
if (num) return num;
else return index + 1;
}
}
const r = new Randp(6);
// 1-6
console.log(r.nextInt());
console.log(r.nextInt());
console.log(r.nextInt());
console.log(r.nextInt());
console.log(r.nextInt());
console.log(r.nextInt());
// 0
console.log(r.nextInt());
console.log(r.nextInt());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment