This would be the general problem statement:
A prisoner escapes from the jail by jumping over N walls each with height of each wall given in an array. He can jump x meters of height, but after every jump he slips y meters due to some uncontrollable factors(wind, slippery wall, etc).
Similar problem statement mentioned here
The programming task given was to debug a function which included four parameters -
NoOfJumps(int x, int y, int N, int Height[])
Number of meters he jumps
Number of meters he slips down the wall
Number of walls
Height of the walls as an array
The first test case was for parameters - (10, 1, 1, {10})
10 being the meters he jumps, 1 meter he slips down, Number of walls being 1, and height of the wall being 10. Now:
effectiveJump = x - y = 9.
So he would have to jump twice to jump over the walls. So, this function should return 2 (total number of jumps required to escape).
There was also another test case for the parameters - (3, 1, 5, {20,5,12,11,3})
3 being the meters he jumps, 1 meter he slips down, Number of walls being 5, and height of the walls given as 20m, 5m, 12m, 11m, 3m. Now:
effectiveJump = x - y = 2.
We were given the output for the above parameter values as 24.
NoOfJumps(3, 1, 5, {20,5,12,11,3})
I can't understand how this output value is obtained. How exactly are the walls arranged?
I can only think of one solution for the corner case, i.e, when the person jumps over the wall
(when (x) > remaining height of the wall),
he should not slip down else I can't obtain the required solution.
For example, in the second test case at first wall, when the person is at 18m height, and he jumps 3m to 21m and doesn't slip down as he has crossed that wall. Next he starts jumping from 21 and not 20. The sequence of jumping would be :
0->2->4->6->8->10->12->14->16->18->21->23->26->28->30->32->34->36->39->41->43->45->47->50->53
Assuming walls at height, 20, 25, 37, 48, 51.
Is this a correct assumption for solving the problem?
C code on given case 2, will work for case 1 on changing the
parameters to (10,1,1,10).
#include<conio.h>
#include<stdio.h>
int jump(int x,int y,int n,int z[]);
int jump(int x,int y,int n,int z[])
{
int i, j, countjump, total = 0, extra = 0;
clrscr();
printf("\n%d\n", n);
for (i = 0; i < n; i++) {
printf("\n%d", z[i]);
}
printf("\n");
for (j = 0; j < n; j++) {
countjump = 1;
z[j] = z[j] + (extra) - x;
while (z[j] >= 0) {
z[j] = z[j] + y;
z[j] = z[j] - x;
countjump = countjump + 1;
if (z[j] < 0) {
extra = z[j];
}
}
total = (countjump + total);
}
return total;
}
void main()
{
int res, manjump = 3, slip = 1, nwalls = 5;
int wallheights[] = {20, 5, 12, 11, 3};
clrscr();
res = jump(manjump, slip, nwalls, wallheights);
printf("\n\ntotal jumps:%d", res);
getch();
}
Try this code. May not be optimized
$input1 = Jump Height
$input2 = Slipage
$input = Array of walls height
function GetJumpCount($input1,$input2,$input3)
{
$jumps = 0;
$wallsCrossed = 0;
while($wallsCrossed != count($input3)){
$jumps++;
$input3[$wallsCrossed] = $input3[$wallsCrossed] - $input1;
if($input3[$wallsCrossed] > 0){
$input3[$wallsCrossed] = $input3[$wallsCrossed] + $input2;
}else{
$wallsCrossed++;
}
}
return $jumps;
}
The walls come one after another. After jumping wall one the position should start from zero and not from the last jump height. For the first case the output should really be 1 as the height and jump are same. In the second test case, 24 is the right output.
I've seen the exact same question on techgig contest. For the first test case the output should be 1. The test case had been explained by themselves where there is no slipping if the jump and height are same.
Try this
You don't require the number of walls as it equals to size of array
public class Jump {
public static void main(String[] a) {
int jump = 3;
int slip = 1;
int[] hights = {20,5,12,11,3};
int count = 0;
for (int hight : hights) {
int temp = hight - jump;
if (temp >= 0) {
count = count + temp / (jump - slip)+1;
}
if (temp % (jump - slip) > 0) {
count++;
}
}
System.out.println(count);
}
}
Logic is here Plz check if this solves your problem.
package puzeels;
public class Jump
{
int jump=6;
int slip=1;
int numberOfWals=4;
int height[] ={21,16,10,5};
static int count=0;
int wallheight=0;
private int findJump()
{
for(int i=0;i<height.length;i++)
{
wallheight=height[i];
while((wallheight>0))
{
count=count+1;
wallheight=wallheight-(jump-slip);
System.out.println(wallheight+" "+count);
}
System.out.println("Out of while loop");
}
return count;
}
public static void main(String arr[])
{
Jump obj = new Jump();
int countOfJumps=obj.findJump();
System.out.println("number of jumps is==> "+countOfJumps);
}
}
You can use this one.
Sample Code
public static int calculateJumps(int X, int Y, int height[]) {
int tn=0,n;
for(int i=0; i<height.length; i++) {
if(height[i]<=X) {
tn+=1;
continue;
}
n=((height[i]-X)/(X-Y));
n+=height[i]-((X-Y)*n)==X?1:2;
tn+=n;
}
return tn;
}
You need to pass only X , Y and Array than you can get you output.
I think 12 is a wrong answer, as I tried this code I got 11, last jump doesn`t have a slip:
public static void main(String [] args) {
int T;
int jcapacity, jslip, nwalls;
//BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
T = sc.nextInt();
jcapacity = sc.nextInt();
jslip = sc.nextInt();
nwalls = sc.nextInt();
int [] wallHeightArr = new int [nwalls];
for (int i = 0; i< nwalls; i++) {
wallHeightArr[i] = sc.nextInt();
}
sc.close();
while(T-->0) {
int distance = log(jcapacity,jslip,wallHeightArr);
System.out.println(distance);
}
}
private static int log(int jcapacity, int jslip, int[] wallHeightArr) {
// TODO Auto-generated method stub
int distance = 0;
for(int i = 0; i< wallHeightArr.length; i++) {
int cHeight = 0;
int count = 0;
while (wallHeightArr[i] - cHeight > jcapacity) {
cHeight += (jcapacity - jslip);
count++;
}
count++;
distance += count;
}
return distance;
}
def jumpTheifCount(arr, X, Y):
jump = 0
remheight = 0
for i in range(len(arr)):
if X == arr[i]:
jump = jump + 1
continue
if X < arr[i]:
jump = jump + 1
remheight = arr[i] - X + Y
if remheight > X:
jump = jump + 1
remheight = arr[i] - X + Y
if remheight < X:
jump = jump + 1
continue
return jump
arr = [11, 10, 10, 9]
X = 10
Y = 1
print(jumpTheifCount(arr, X, Y))
check if this solves your problem
def GetJumpCount(jump, slips, walls):
"""
#jump:int, Height of 1 jump
#slips:int, height of slip
#walls:array, height of walls
"""
jumps = []
for wall_height in walls:
wall_jump = 1
wall_height -= jump
while wall_height > 0:
wall_height += slips
wall_height -= jump
wall_jump += 1
jumps.append(wall_jump)
return sum(jumps)
Related
What I want to do is to create a new planet in my system for example every 10 seconds and that it starts to move and also prints a "hello" . At the end I want that the 8 planets (ellipses) will be moving together.
I try to use delay(); but I failed .
Can someone help me please?
Planet [] planetCollection = new Planet [8];
float [] wid2 = {100,200,300,400,500,600,700,800};
float [] hig2 = {50,75,100,125,150,175,200,225};
int [] colorR = {100,800,300,400,500,600,700,800};
int [] colorG = {50,225,100,125,150,175,200,225};
int [] colorB = {50,225,100,125,150,175,200,225};
int [] size = {10,12,14,16,18,20,22,24};
int lastTime =0;
int contador =0;
void setup (){
size (1600,1600);
smooth();
//INITIALIZE
for (int i=0 ; i<planetCollection.length; i++){
planetCollection [i] = new Planet(wid2[i], hig2[i], colorR[i],
colorG[i], colorB[i], size[i]);
}
}
void draw (){
background (0);
//CALL FUNCIONALITY
for (int i=0 ; i<planetCollection.length; i++){
planetCollection [i].run();
}
}
class Planet {
//GLOBAL VARIABLES
float val;
float x = 0;
float y = 0;
float wid2;
float hig2;
float speed;
int colorR;
int colorG;
int colorB;
int size;
int centerx = width/2;
int centery = height/4;
//CONTRUCTOR
Planet(float _w, float _h,int _colorR,int _colorG,int _colorB, int _size){
wid2=_w;
hig2=_h;
colorR= _colorR;
colorG= _colorG;
colorB= _colorB;
size = _size;
speed=10/(2*PI * sqrt ((pow(wid2,2)+pow (hig2,2)/2))); ;
}
//FUNCTIONS
void run (){
move();
display();
}
void move (){
x= sin (val);
y= cos(val);
x *=wid2;
y *=hig2;
//SUN/CENTER
noStroke();
fill (255,238,41);
ellipse (centerx,centery,40,40);
if (dist (mouseX,mouseY,centerx,centery)<20){
if(mousePressed){
speed =0;
}
}
//
x+= centerx;
y+= centery;
val += speed;
}
void display (){
//PLanets
fill(colorR, colorG, colorB);
ellipse(x, y, size, size);
///Orbits
noFill();
stroke(255);
ellipse(centerx, centery, wid2*2, hig2*2);
println ("posicionx "+x);
println ("posiciony "+y);
println ("width "+wid2);
println ("high "+hig2);
println ("val "+val);
println ("speed "+speed);
}
}
You can use the modulo % operator along with the frameCount variable inside the draw() function to do something every X frames.
Here is an example program that draws little circles most frames, but draws a big circle every 60 frames:
void setup() {
size(500, 500);
background(0);
}
void draw() {
ellipse(mouseX, mouseY, 10, 10);
if (frameCount % 60 == 0) {
ellipse(mouseX, mouseY, 50, 50);
}
}
You can build a timer for counting seconds using a helper variable and the in-built variable frameRate. (Note that this solution ensures that you truly count seconds independent on your machine's current workload.)
frameRate tells you how many cycles Processing is currently performing per second (one cycle = one execution of draw, also called one frame). This is usually 60 (frames per second) but can also be lower depending on other processes on your machine (e.g. when running video processing, 3D games etc. the frame rate goes down).
Here's a snippet to see what your current frameRate is:
void draw() {
println(frameRate);
}
And here's the timer using a helper variable counter which is reset every second. You should see a new dot appear on the console output every second.
int counter = 0;
void draw() {
if (counter > frameRate) {
print(".");
counter = 0;
} else {
counter++;
}
}
To make it count every 10 seconds you can just change the if condition to "counter > 10 * frameRate".
I need to extract bit of a decimal number.
for example, y=52 (110100 to binary) and j=2..
so i need to return 1...
if j=3 return 0...
this is my function...
function int multiply(int x, int y) {
var int tx;
var int ty;
let tx = x;
let ty = y;
let tx = Math.abs(x);
let ty = Math.abs(y);
var int shiftedX;
let shiftedX = tx;
var int result;
let result = 0;
var int i;
let i = 0;
while(i<16){
if( i-th bit of ty = 1 )//pseudo code...
{
let result = result + shiftedX;
}
let shiftedX = shiftedX + shiftedX;
}
if(((x > 0) & (y < 0)) | ((x < 0) & (y > 0))){
return -result;
}
return result;
}
I wrote in the "if" pseudo code
How can i do this with really code??
Jack appears to lack bitshifts, but that's OK, we can make the right mask in the same way as shiftedX is kept current (instead of doing tx << i), like this:
var int shiftedX;
let shiftedX = x;
var int mask;
let mask = 1;
var int i;
let i = 0;
while(i < 16){
if((y & mask) = mask)
{
let result = result + shiftedX;
}
let shiftedX = shiftedX + shiftedX;
let mask = mask + mask;
let i = i + 1;
}
You can leave out the abs stuff and the sign-fix on the end (as long as you leave them both out), signed and unsigned multiplication are the same thing.
At the time of answering this question, it was tagged under C or C++...
First of all, get rid of the following symbols (as they are not part of the language):
- function
- var
- let
As to your question, you can use the following piece of code:
for (i=0; i<16; i++)
{
if ((ty>>i) & 1)
{
result += shiftedX;
}
shiftedX <<= 1;
}
I'm one of the moderators at the official Nand2Tetris help forum
http://nand2tetris-questions-and-answers-forum.32033.n3.nabble.com/
Be sure to check and post there for help, too.
Regarding signed versus unsigned multiplication:
When you multiply two 16-bit numbers, you get a 32-bit result. The bottom 16-bits of this result is the same whether the numbers you are multiplying are signed or unsigned; only the upper 16-bits are different.
Since the Math.multiply routine only returns 16 bits, you don't need to worry about the signs of x and y.
I want to make a sliding menu just like the level menu in which on one screen there will be 40 sprites labelled as level 1 level 2 respectively up to 40.
At the bottom right there will be another sprite with a arrow to which when I click it should slide to other screen and show the levels 41 to 80.Please provide me with a basic concept how to use it.I will be thankful to you.
Note: I am using Xcode and ony want solution in cocos2d-x using c++
This is the way I have done this in the past...I had a game with the option for the player to select multiple space ships, 4 per page, with back/forward arrows on each page as well.
Create a CCScene derived class.
Place all your menu items, including the control arrows for ALL pages on it. You will have to space all the items so the items for the first page are on the visible part of the screen and the next group is 100% off to the right, the third group is 200% off the right, etc.
The control buttons on the scene start an action to move the layer 100% to the left (if they move right) or 100% to the right (if they move left).
All of these are attached to a single "Menu", which is what the actions are applied against. If you want, you can put the menu into a layer (so it has background that moves). This is up to you.
In the example Scene below, I just used a simple menu.
MainScene.h
#ifndef __MainScene__
#define __MainScene__
#include "cocos2d.h"
using namespace cocos2d;
class MainScene : public CCScene
{
private:
// This class follows the "create"/"autorelease" pattern.
// Private constructor.
MainScene();
CCMenu* _menu;
bool _sliding;
void MenuCallback(CCObject* sender);
void PageLeft();
void PageRight();
void SlidingDone();
protected:
// This is protected so that derived classes can call it
// in their create methods.
bool init();
private:
void CreateMenu();
public:
static MainScene* create();
~MainScene();
virtual void onEnter();
virtual void onExit();
virtual void onEnterTransitionDidFinish();
virtual void onExitTransitionDidStart();
};
#endif /* defined(__MainScene__) */
MainScene.cpp
#include "MainScene.h"
#define ARROW_LEFT (-1)
#define ARROW_RIGHT (-2)
#define MENU_ITEMS_ACROSS 4
#define MENU_ITEMS_DOWN 5
#define MENU_ITEMS_PAGE (MENU_ITEMS_ACROSS*MENU_ITEMS_DOWN)
#define MENU_ITEMS_TOTAL 50
#define MENU_PAGES ((MENU_ITEMS_TOTAL/MENU_ITEMS_PAGE)+1)
#define MENU_FRACTION (ccp(0.8,0.8))
#define MENU_ANCHOR (ccp(0.5,0.5))
#define SLIDE_DURATION 1.0
MainScene::MainScene() :
_menu(NULL)
_sliding(false)
{
}
MainScene::~MainScene()
{
}
static CCPoint CalculatePosition(int itemNum)
{
CCSize scrSize = CCDirector::sharedDirector()->getWinSize();
float Xs = scrSize.width;
float Ys = scrSize.height;
int gRows = MENU_ITEMS_DOWN;
int gCols = MENU_ITEMS_ACROSS;
int gBins = gRows*gCols;
float Xb = MENU_FRACTION.x*Xs/gCols;
float Yb = MENU_FRACTION.y*Ys/gRows;
float Xa = MENU_ANCHOR.x * Xs;
float Ya = MENU_ANCHOR.y * Ys;
int page = itemNum / gBins;
int binCol = itemNum % gCols;
int binRow = (itemNum-page*gBins) / gCols;
float xPos = binCol * Xb + Xb/2 + Xa - MENU_FRACTION.x*Xs/2 + page * Xs;
float yPos = Ya - binRow*Yb - Yb/2 + MENU_FRACTION.y * Ys/2;
CCPoint pos = ccp(xPos,yPos);
return pos;
}
void MainScene::CreateMenu()
{
if(_menu == NULL)
{
CCSize scrSize = CCDirector::sharedDirector()->getWinSize();
_menu = CCMenu::create();
_menu->setPosition(ccp(0,0));
addChild(_menu);
CCMenuItemFont* pItem;
CCPoint position;
// Create the next/back menu items.
for(int page = 0; page < MENU_PAGES; page++)
{
// Create the Back/Forward buttons for the page.
// Back arrow if there is a previous page.
if(page > 0)
{
pItem = CCMenuItemFont::create("Back", this, menu_selector(MainScene::MenuCallback));
pItem->setTag(ARROW_LEFT);
position = ccp(page*scrSize.width + scrSize.width*0.1,scrSize.height*0.1);
pItem->setPosition(position);
pItem->setFontSize(35);
pItem->setFontName("Arial");
_menu->addChild(pItem);
}
if(page < (MENU_PAGES-1))
{
pItem = CCMenuItemFont::create("Next", this, menu_selector(MainScene::MenuCallback));
pItem->setTag(ARROW_RIGHT);
position = ccp(page*scrSize.width + scrSize.width*0.9,scrSize.height*0.1);
pItem->setPosition(position);
pItem->setFontSize(35);
pItem->setFontName("Arial");
_menu->addChild(pItem);
}
}
// Create the actual items
for(int idx = 0; idx < MENU_ITEMS_TOTAL; idx++)
{
char buffer[256];
sprintf(buffer,"Item #%d",idx);
pItem = CCMenuItemFont::create(buffer, this, menu_selector(MainScene::MenuCallback));
pItem->setFontSize(35);
pItem->setFontName("Arial");
pItem->setTag(idx);
position = CalculatePosition(idx);
pItem->setPosition(position);
_menu->addChild(pItem);
}
}
}
bool MainScene::init()
{
return true;
}
MainScene* MainScene::create()
{
MainScene *pRet = new MainScene();
if (pRet && pRet->init())
{
pRet->autorelease();
return pRet;
}
else
{
CC_SAFE_DELETE(pRet);
return NULL;
}
}
void MainScene::onEnter()
{
CCScene::onEnter();
CreateMenu();
}
void MainScene::onExit()
{
CCScene::onExit();
}
void MainScene::onEnterTransitionDidFinish()
{
CCScene::onEnterTransitionDidFinish();
}
void MainScene::onExitTransitionDidStart()
{
CCScene::onExitTransitionDidStart();
}
void MainScene::SlidingDone()
{
_sliding = false;
}
void MainScene::PageLeft()
{
if(_sliding)
return;
_sliding = true;
CCSize scrSize = CCDirector::sharedDirector()->getWinSize();
CCFiniteTimeAction* act1 = CCMoveBy::create(SLIDE_DURATION, ccp(scrSize.width,0));
CCFiniteTimeAction* act2 = CCCallFunc::create(this, callfunc_selector(MainScene::SlidingDone));
_menu->runAction(CCSequence::create(act1,act2,NULL));
}
void MainScene::PageRight()
{
if(_sliding)
return;
_sliding = true;
CCSize scrSize = CCDirector::sharedDirector()->getWinSize();
CCFiniteTimeAction* act1 = CCMoveBy::create(SLIDE_DURATION, ccp(-scrSize.width,0));
CCFiniteTimeAction* act2 = CCCallFunc::create(this, callfunc_selector(MainScene::SlidingDone));
_menu->runAction(CCSequence::create(act1,act2,NULL));
}
void MainScene::MenuCallback(CCObject* sender)
{
// This is a very contrived example
// for handling the menu items.
// -1 ==> Left Arrow
// -2 ==> Right Arrow
// Anything else is a selection
CCMenuItem* pMenuItem = (CCMenuItem*)sender;
switch(pMenuItem->getTag())
{
case ARROW_LEFT:
PageLeft();
break;
case ARROW_RIGHT:
PageRight();
break;
default:
CCLOG("Got Item %d Pressed",pMenuItem->getTag());
break;
}
}
Note The formulas for getting the items spread across several pages can be a little tricky. There is a notion of "Screen fraction", which is how much the grid of items takes up on the page. There is also the notion of "menu anchor", which where on the page you want the grid to be.
Some screen shots
or you can do it the modern way with less code!!
// you have to include this header to use the ui classes
#include "ui/CocosGUI.h"
using namespace ui;
#define COLS 4
#define ROWS 4
#define ITEMS_PER_PAGE (ROWS * COLS)
#define TOTAL_PAGES_NUM 10
#define MENU_PADDING (Vec2(0.8,0.8))
#define MENU_ANCHOR (Vec2(0.5,0.5))
static Vec2 calcPosition(int itemNum)
{
Size scrSize = Director::getInstance()->getWinSize();
float Xs = scrSize.width;
float Ys = scrSize.height;
float Xb = MENU_PADDING.x*Xs / COLS;
float Yb = MENU_PADDING.y*Ys / ROWS;
float Xa = MENU_ANCHOR.x * Xs;
float Ya = MENU_ANCHOR.y * Ys;
int page = itemNum / ITEMS_PER_PAGE;
int binCol = itemNum % COLS;
int binRow = (itemNum - page * ITEMS_PER_PAGE) / COLS;
float xPos = binCol * Xb + Xb / 2 + Xa - MENU_PADDING.x*Xs / 2 + page * Xs;
float yPos = Ya - binRow*Yb - Yb / 2 + MENU_PADDING.y * Ys / 2;
return Vec2(xPos, yPos);
}
//init method
// pageView is the container that will contain all pages
auto pageView = PageView::create();
pageView->setContentSize(winSize);
//if you want pages indicator just uncomment this
//pageView->setIndicatorEnabled(true);
//pageView->setIndicatorPosition(some position);
//pageView->setIndicatorSelectedIndexColor(some Color3B);
for (int i = 0; i < TOTAL_PAGES_NUM; i++) {
auto layout = Layout::create();
layout->setContentSize(winSize);
// give each page a different random color
int r = rand() % 200;
int g = rand() % 200;
int b = rand() % 200;
auto bg = LayerColor::create(Color4B(Color3B(r, g, b)), winSize.width, winSize.height);
layout->addChild(bg, 0);
// populate each single page with items (which are in this case labels)
for (int i = 0; i < ITEMS_PER_PAGE; i++) {
auto label = LabelTTF::create(StringUtils::format("item %i", (i + 1)), "Comic Sans MS", 15);
Vec2 pos = calcPosition(i);
label->setPosition(pos);
layout->addChild(label, 1);
}
pageView->addPage(layout);
}
this->addChild(pageView);
I’ve modified existing one and uploaded in github. Here is the link:
GitHub Link to SlidingMenu
You may find it helpful. You can directly add it into your game.
I need to calculate permutations iteratively. The method signature looks like:
int[][] permute(int n)
For n = 3 for example, the return value would be:
[[0,1,2],
[0,2,1],
[1,0,2],
[1,2,0],
[2,0,1],
[2,1,0]]
How would you go about doing this iteratively in the most efficient way possible? I can do this recursively, but I'm interested in seeing lots of alternate ways to doing it iteratively.
see QuickPerm algorithm, it's iterative : http://www.quickperm.org/
Edit:
Rewritten in Ruby for clarity:
def permute_map(n)
results = []
a, p = (0...n).to_a, [0] * n
i, j = 0, 0
i = 1
results << yield(a)
while i < n
if p[i] < i
j = i % 2 * p[i] # If i is odd, then j = p[i], else j = 0
a[j], a[i] = a[i], a[j] # Swap
results << yield(a)
p[i] += 1
i = 1
else
p[i] = 0
i += 1
end
end
return results
end
The algorithm for stepping from one permutation to the next is very similar to elementary school addition - when an overflow occurs, "carry the one".
Here's an implementation I wrote in C:
#include <stdio.h>
//Convenience macro. Its function should be obvious.
#define swap(a,b) do { \
typeof(a) __tmp = (a); \
(a) = (b); \
(b) = __tmp; \
} while(0)
void perm_start(unsigned int n[], unsigned int count) {
unsigned int i;
for (i=0; i<count; i++)
n[i] = i;
}
//Returns 0 on wraparound
int perm_next(unsigned int n[], unsigned int count) {
unsigned int tail, i, j;
if (count <= 1)
return 0;
/* Find all terms at the end that are in reverse order.
Example: 0 3 (5 4 2 1) (i becomes 2) */
for (i=count-1; i>0 && n[i-1] >= n[i]; i--);
tail = i;
if (tail > 0) {
/* Find the last item from the tail set greater than
the last item from the head set, and swap them.
Example: 0 3* (5 4* 2 1)
Becomes: 0 4* (5 3* 2 1) */
for (j=count-1; j>tail && n[j] <= n[tail-1]; j--);
swap(n[tail-1], n[j]);
}
/* Reverse the tail set's order */
for (i=tail, j=count-1; i<j; i++, j--)
swap(n[i], n[j]);
/* If the entire list was in reverse order, tail will be zero. */
return (tail != 0);
}
int main(void)
{
#define N 3
unsigned int perm[N];
perm_start(perm, N);
do {
int i;
for (i = 0; i < N; i++)
printf("%d ", perm[i]);
printf("\n");
} while (perm_next(perm, N));
return 0;
}
Is using 1.9's Array#permutation an option?
>> a = [0,1,2].permutation(3).to_a
=> [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]
Below is my generics version of the next permutation algorithm in C# closely resembling the STL's next_permutation function (but it doesn't reverse the collection if it is the max possible permutation already, like the C++ version does)
In theory it should work with any IList<> of IComparables.
static bool NextPermutation<T>(IList<T> a) where T: IComparable
{
if (a.Count < 2) return false;
var k = a.Count-2;
while (k >= 0 && a[k].CompareTo( a[k+1]) >=0) k--;
if(k<0)return false;
var l = a.Count - 1;
while (l > k && a[l].CompareTo(a[k]) <= 0) l--;
var tmp = a[k];
a[k] = a[l];
a[l] = tmp;
var i = k + 1;
var j = a.Count - 1;
while(i<j)
{
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
i++;
j--;
}
return true;
}
And the demo/test code:
var src = "1234".ToCharArray();
do
{
Console.WriteLine(src);
}
while (NextPermutation(src));
I also came across the QuickPerm algorithm referenced in another answer. I wanted to share this answer in addition, because I saw some immediate changes one can make to write it shorter. For example, if the index array "p" is initialized slightly differently, it saves having to return the first permutation before the loop. Also, all those while-loops and if's took up a lot more room.
void permute(char* s, size_t l) {
int* p = new int[l];
for (int i = 0; i < l; i++) p[i] = i;
for (size_t i = 0; i < l; printf("%s\n", s)) {
std::swap(s[i], s[i % 2 * --p[i]]);
for (i = 1; p[i] == 0; i++) p[i] = i;
}
}
I found Joey Adams' version to be the most readable, but I couldn't port it directly to C# because of how C# handles the scoping of for-loop variables. Hence, this is a slightly tweaked version of his code:
/// <summary>
/// Performs an in-place permutation of <paramref name="values"/>, and returns if there
/// are any more permutations remaining.
/// </summary>
private static bool NextPermutation(int[] values)
{
if (values.Length == 0)
throw new ArgumentException("Cannot permutate an empty collection.");
//Find all terms at the end that are in reverse order.
// Example: 0 3 (5 4 2 1) (i becomes 2)
int tail = values.Length - 1;
while(tail > 0 && values[tail - 1] >= values[tail])
tail--;
if (tail > 0)
{
//Find the last item from the tail set greater than the last item from the head
//set, and swap them.
// Example: 0 3* (5 4* 2 1)
// Becomes: 0 4* (5 3* 2 1)
int index = values.Length - 1;
while (index > tail && values[index] <= values[tail - 1])
index--;
Swap(ref values[tail - 1], ref values[index]);
}
//Reverse the tail set's order.
int limit = (values.Length - tail) / 2;
for (int index = 0; index < limit; index++)
Swap(ref values[tail + index], ref values[values.Length - 1 - index]);
//If the entire list was in reverse order, tail will be zero.
return (tail != 0);
}
private static void Swap<T>(ref T left, ref T right)
{
T temp = left;
left = right;
right = temp;
}
Here's an implementation in C#, as an extension method:
public static IEnumerable<List<T>> Permute<T>(this IList<T> items)
{
var indexes = Enumerable.Range(0, items.Count).ToArray();
yield return indexes.Select(idx => items[idx]).ToList();
var weights = new int[items.Count];
var idxUpper = 1;
while (idxUpper < items.Count)
{
if (weights[idxUpper] < idxUpper)
{
var idxLower = idxUpper % 2 * weights[idxUpper];
var tmp = indexes[idxLower];
indexes[idxLower] = indexes[idxUpper];
indexes[idxUpper] = tmp;
yield return indexes.Select(idx => items[idx]).ToList();
weights[idxUpper]++;
idxUpper = 1;
}
else
{
weights[idxUpper] = 0;
idxUpper++;
}
}
}
And a unit test:
[TestMethod]
public void Permute()
{
var ints = new[] { 1, 2, 3 };
var orderings = ints.Permute().ToList();
Assert.AreEqual(6, orderings.Count);
AssertUtil.SequencesAreEqual(new[] { 1, 2, 3 }, orderings[0]);
AssertUtil.SequencesAreEqual(new[] { 2, 1, 3 }, orderings[1]);
AssertUtil.SequencesAreEqual(new[] { 3, 1, 2 }, orderings[2]);
AssertUtil.SequencesAreEqual(new[] { 1, 3, 2 }, orderings[3]);
AssertUtil.SequencesAreEqual(new[] { 2, 3, 1 }, orderings[4]);
AssertUtil.SequencesAreEqual(new[] { 3, 2, 1 }, orderings[5]);
}
The method AssertUtil.SequencesAreEqual is a custom test helper which can be recreated easily enough.
How about a recursive algorithm you can call iteratively? If you'd actually need that stuff as a list like that (you should clearly inline that rather than allocate a bunch of pointless memory). You could simply calculate the permutation on the fly, by its index.
Much like the permutation is carry-the-one addition re-reversing the tail (rather than reverting to 0), indexing the specific permutation value is finding the digits of a number in base n then n-1 then n-2... through each iteration.
public static <T> boolean permutation(List<T> values, int index) {
return permutation(values, values.size() - 1, index);
}
private static <T> boolean permutation(List<T> values, int n, int index) {
if ((index == 0) || (n == 0)) return (index == 0);
Collections.swap(values, n, n-(index % n));
return permutation(values,n-1,index/n);
}
The boolean returns whether your index value was out of bounds. Namely that it ran out of n values but still had remaining index left over.
And it can't get all the permutations for more than 12 objects.
12! < Integer.MAX_VALUE < 13!
-- But, it's so very very pretty. And if you do a lot of things wrong might be useful.
I have implemented the algorithm in Javascript.
var all = ["a", "b", "c"];
console.log(permute(all));
function permute(a){
var i=1,j, temp = "";
var p = [];
var n = a.length;
var output = [];
output.push(a.slice());
for(var b=0; b <= n; b++){
p[b] = b;
}
while (i < n){
p[i]--;
if(i%2 == 1){
j = p[i];
}
else{
j = 0;
}
temp = a[j];
a[j] = a[i];
a[i] = temp;
i=1;
while (p[i] === 0){
p[i] = i;
i++;
}
output.push(a.slice());
}
return output;
}
I've used the algorithms from here. The page contains a lot of useful information.
Edit: Sorry, those were recursive. uray posted the link to the iterative algorithm in his answer.
I've created a PHP example. Unless you really need to return all of the results, I would only create an iterative class like the following:
<?php
class Permutator implements Iterator
{
private $a, $n, $p, $i, $j, $k;
private $stop;
public function __construct(array $a)
{
$this->a = array_values($a);
$this->n = count($this->a);
}
public function current()
{
return $this->a;
}
public function next()
{
++$this->k;
while ($this->i < $this->n)
{
if ($this->p[$this->i] < $this->i)
{
$this->j = ($this->i % 2) * $this->p[$this->i];
$tmp = $this->a[$this->j];
$this->a[$this->j] = $this->a[$this->i];
$this->a[$this->i] = $tmp;
$this->p[$this->i]++;
$this->i = 1;
return;
}
$this->p[$this->i++] = 0;
}
$this->stop = true;
}
public function key()
{
return $this->k;
}
public function valid()
{
return !$this->stop;
}
public function rewind()
{
if ($this->n) $this->p = array_fill(0, $this->n, 0);
$this->stop = $this->n == 0;
$this->i = 1;
$this->j = 0;
$this->k = 0;
}
}
foreach (new Permutator(array(1,2,3,4,5)) as $permutation)
{
var_dump($permutation);
}
?>
Note that it treats every PHP array as an indexed array.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Not so long ago I was in an interview, that required solving two very interesting problems. I'm curious how would you approach the solutions.
Problem 1 :
Product of everything except current
Write a function that takes as input two integer arrays of length len, input and index, and generates a third array, result, such that:
result[i] = product of everything in input except input[index[i]]
For instance, if the function is called with len=4, input={2,3,4,5}, and index={1,3,2,0}, then result will be set to {40,24,30,60}.
IMPORTANT: Your algorithm must run in linear time.
Problem 2 : ( the topic was in one of Jeff posts )
Shuffle card deck evenly
Design (either in C++ or in C#) a class Deck to represent an ordered deck of cards, where a deck contains 52 cards, divided in 13 ranks (A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K) of the four suits: spades (?), hearts (?), diamonds (?) and clubs (?).
Based on this class, devise and implement an efficient algorithm to shuffle a deck of cards. The cards must be evenly shuffled, that is, every card in the original deck must have the same probability to end up in any possible position in the shuffled deck.
The algorithm should be implemented in a method shuffle() of the class Deck:
void shuffle()
What is the complexity of your algorithm (as a function of the number n of cards in the deck)?
Explain how you would test that the cards are evenly shuffled by your method (black box testing).
P.S. I had two hours to code the solutions
First question:
int countZeroes (int[] vec) {
int ret = 0;
foreach(int i in vec) if (i == 0) ret++;
return ret;
}
int[] mysticCalc(int[] values, int[] indexes) {
int zeroes = countZeroes(values);
int[] retval = new int[values.length];
int product = 1;
if (zeroes >= 2) { // 2 or more zeroes, all results will be 0
for (int i = 0; i > values.length; i++) {
retval[i] = 0;
}
return retval;
}
foreach (int i in values) {
if (i != 0) product *= i; // we have at most 1 zero, dont include in product;
}
int indexcounter = 0;
foreach(int idx in indexes) {
if (zeroes == 1 && values[idx] != 0) { // One zero on other index. Our value will be 0
retval[indexcounter] = 0;
}
else if (zeroes == 1) { // One zero on this index. result is product
retval[indexcounter] = product;
}
else { // No zeros. Return product/value at index
retval[indexcounter] = product / values[idx];
}
indexcouter++;
}
return retval;
}
Worst case this program will step through 3 vectors once.
For the first one, first calculate the product of entire contents of input, and then for every element of index, divide the calculated product by input[index[i]], to fill in your result array.
Of course I have to assume that the input has no zeros.
Tnilsson, great solution ( because I've done it the exact same way :P ).
I don't see any other way to do it in linear time. Does anybody ? Because the recruiting manager told me, that this solution was not strong enough.
Are we missing some super complex, do everything in one return line, solution ?
A linear-time solution in C#3 for the first problem is:-
IEnumerable<int> ProductExcept(List<int> l, List<int> indexes) {
if (l.Count(i => i == 0) == 1) {
int singleZeroProd = l.Aggregate(1, (x, y) => y != 0 ? x * y : x);
return from i in indexes select l[i] == 0 ? singleZeroProd : 0;
} else {
int prod = l.Aggregate(1, (x, y) => x * y);
return from i in indexes select prod == 0 ? 0 : prod / l[i];
}
}
Edit: Took into account a single zero!! My last solution took me 2 minutes while I was at work so I don't feel so bad :-)
Product of everything except current in C
void product_except_current(int input[], int index[], int out[],
int len) {
int prod = 1, nzeros = 0, izero = -1;
for (int i = 0; i < len; ++i)
if ((out[i] = input[index[i]]) != 0)
// compute product of non-zero elements
prod *= out[i]; // ignore possible overflow problem
else {
if (++nzeros == 2)
// if number of zeros greater than 1 then out[i] = 0 for all i
break;
izero = i; // save index of zero-valued element
}
//
for (int i = 0; i < len; ++i)
out[i] = nzeros ? 0 : prod / out[i];
if (nzeros == 1)
out[izero] = prod; // the only non-zero-valued element
}
Here's the answer to the second one in C# with a test method. Shuffle looks O(n) to me.
Edit: Having looked at the Fisher-Yates shuffle, I discovered that I'd re-invented that algorithm without knowing about it :-) it is obvious, however. I implemented the Durstenfeld approach which takes us from O(n^2) -> O(n), really clever!
public enum CardValue { A, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, J, Q, K }
public enum Suit { Spades, Hearts, Diamonds, Clubs }
public class Card {
public Card(CardValue value, Suit suit) {
Value = value;
Suit = suit;
}
public CardValue Value { get; private set; }
public Suit Suit { get; private set; }
}
public class Deck : IEnumerable<Card> {
public Deck() {
initialiseDeck();
Shuffle();
}
private Card[] cards = new Card[52];
private void initialiseDeck() {
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 13; ++j) {
cards[i * 13 + j] = new Card((CardValue)j, (Suit)i);
}
}
}
public void Shuffle() {
Random random = new Random();
for (int i = 0; i < 52; ++i) {
int j = random.Next(51 - i);
// Swap the cards.
Card temp = cards[51 - i];
cards[51 - i] = cards[j];
cards[j] = temp;
}
}
public IEnumerator<Card> GetEnumerator() {
foreach (Card c in cards) yield return c;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
foreach (Card c in cards) yield return c;
}
}
class Program {
static void Main(string[] args) {
foreach (Card c in new Deck()) {
Console.WriteLine("{0} of {1}", c.Value, c.Suit);
}
Console.ReadKey(true);
}
}
In Haskell:
import Array
problem1 input index = [(left!i) * (right!(i+1)) | i <- index]
where left = scanWith scanl
right = scanWith scanr
scanWith scan = listArray (0, length input) (scan (*) 1 input)
Vaibhav, unfortunately we have to assume, that there could be a 0 in the input table.
Second problem.
public static void shuffle (int[] array)
{
Random rng = new Random(); // i.e., java.util.Random.
int n = array.length; // The number of items left to shuffle (loop invariant).
while (n > 1)
{
int k = rng.nextInt(n); // 0 <= k < n.
n--; // n is now the last pertinent index;
int temp = array[n]; // swap array[n] with array[k] (does nothing if k == n).
array[n] = array[k];
array[k] = temp;
}
}
This is a copy/paste from the wikipedia article about the Fisher-Yates shuffle. O(n) complexity
Tnilsson, I agree that YXJuLnphcnQ solution is arguably faster, but the idee is the same. I forgot to add, that the language is optional in the first problem, as well as int the second.
You're right, that calculationg zeroes, and the product int the same loop is better. Maybe that was the thing.
Tnilsson, I've also uset the Fisher-Yates shuffle :). I'm very interested dough, about the testing part :)
Trilsson made a separate topic about the testing part of the question
How to test randomness (case in point - Shuffling)
very good idea Trilsson:)
YXJuLnphcnQ, that's the way I did it too. It's the most obvious.
But the fact is, that if you write an algorithm, that just shuffles all the cards in the collection one position to the right every time you call sort() it would pass the test, even though the output is not random.
Shuffle card deck evenly in C++
#include <algorithm>
class Deck {
// each card is 8-bit: 4-bit for suit, 4-bit for value
// suits and values are extracted using bit-magic
char cards[52];
public:
// ...
void shuffle() {
std::random_shuffle(cards, cards + 52);
}
// ...
};
Complexity: Linear in N. Exactly 51 swaps are performed. See http://www.sgi.com/tech/stl/random_shuffle.html
Testing:
// ...
int main() {
typedef std::map<std::pair<size_t, Deck::value_type>, size_t> Map;
Map freqs;
Deck d;
const size_t ntests = 100000;
// compute frequencies of events: card at position
for (size_t i = 0; i < ntests; ++i) {
d.shuffle();
size_t pos = 0;
for(Deck::const_iterator j = d.begin(); j != d.end(); ++j, ++pos)
++freqs[std::make_pair(pos, *j)];
}
// if Deck.shuffle() is correct then all frequencies must be similar
for (Map::const_iterator j = freqs.begin(); j != freqs.end(); ++j)
std::cout << "pos=" << j->first.first << " card=" << j->first.second
<< " freq=" << j->second << std::endl;
}
As usual, one test is not sufficient.